meshagent-telegram 0.44.11__tar.gz
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.
- meshagent_telegram-0.44.11/CHANGELOG.md +2 -0
- meshagent_telegram-0.44.11/LICENSE +201 -0
- meshagent_telegram-0.44.11/MANIFEST.in +1 -0
- meshagent_telegram-0.44.11/PKG-INFO +22 -0
- meshagent_telegram-0.44.11/README.md +6 -0
- meshagent_telegram-0.44.11/meshagent/telegram/__init__.py +4 -0
- meshagent_telegram-0.44.11/meshagent/telegram/channel.py +362 -0
- meshagent_telegram-0.44.11/meshagent/telegram/version.py +1 -0
- meshagent_telegram-0.44.11/meshagent_telegram.egg-info/PKG-INFO +22 -0
- meshagent_telegram-0.44.11/meshagent_telegram.egg-info/SOURCES.txt +14 -0
- meshagent_telegram-0.44.11/meshagent_telegram.egg-info/dependency_links.txt +1 -0
- meshagent_telegram-0.44.11/meshagent_telegram.egg-info/requires.txt +3 -0
- meshagent_telegram-0.44.11/meshagent_telegram.egg-info/top_level.txt +1 -0
- meshagent_telegram-0.44.11/pyproject.toml +30 -0
- meshagent_telegram-0.44.11/setup.cfg +4 -0
- meshagent_telegram-0.44.11/tests/test_telegram_channel.py +25 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
include CHANGELOG.md
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-telegram
|
|
3
|
+
Version: 0.44.11
|
|
4
|
+
Summary: Telegram channel support for MeshAgent
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: meshagent-api==0.44.11
|
|
13
|
+
Requires-Dist: meshagent-agents==0.44.11
|
|
14
|
+
Requires-Dist: telethon<2,>=1.36
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# MeshAgent Telegram
|
|
18
|
+
|
|
19
|
+
Telegram account channel support for MeshAgent process agents.
|
|
20
|
+
|
|
21
|
+
This package exports `TelegramChannel` and `create_channel(...)` for use with a
|
|
22
|
+
MeshAgent process channel shim.
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import uuid
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from meshagent.agents.adapter import LLMAdapter
|
|
12
|
+
from meshagent.agents.messages import (
|
|
13
|
+
AGENT_MESSAGE_TURN_START,
|
|
14
|
+
AgentTextContent,
|
|
15
|
+
AgentTextContentDelta,
|
|
16
|
+
ThreadCleared,
|
|
17
|
+
TurnEnded,
|
|
18
|
+
TurnStart,
|
|
19
|
+
TurnStarted,
|
|
20
|
+
TurnStartRejected,
|
|
21
|
+
)
|
|
22
|
+
from meshagent.agents.process import Message
|
|
23
|
+
from meshagent.agents.threaded_channel import ThreadedChannel
|
|
24
|
+
from meshagent.api import Participant, RoomClient
|
|
25
|
+
from telethon import TelegramClient, events
|
|
26
|
+
from telethon.sessions import StringSession
|
|
27
|
+
from telethon.tl.types import Channel, Chat, User
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("meshagent.telegram_channel")
|
|
31
|
+
|
|
32
|
+
THREAD_PREFIX = os.getenv("MESHAGENT_TELEGRAM_THREAD_PREFIX", ".threads/telegram")
|
|
33
|
+
MAX_TELEGRAM_MESSAGE_CHARS = 3900
|
|
34
|
+
RESPONSE_TIMEOUT_SECONDS = float(
|
|
35
|
+
os.getenv("MESHAGENT_TELEGRAM_RESPONSE_TIMEOUT", "300")
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(slots=True)
|
|
40
|
+
class _PendingTelegramTurn:
|
|
41
|
+
chat_id: object
|
|
42
|
+
response: asyncio.Future[str]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(slots=True)
|
|
46
|
+
class _ActiveTelegramTurn:
|
|
47
|
+
chat_id: object
|
|
48
|
+
response: asyncio.Future[str]
|
|
49
|
+
text_parts: list[str] = field(default_factory=list)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def required_env(name: str) -> str:
|
|
53
|
+
value = os.getenv(name, "").strip()
|
|
54
|
+
if value == "":
|
|
55
|
+
raise RuntimeError(f"Set {name} before starting the Telegram channel.")
|
|
56
|
+
return value
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def telegram_chunks(text: str) -> list[str]:
|
|
60
|
+
normalized = text.strip()
|
|
61
|
+
if normalized == "":
|
|
62
|
+
return ["The room agent returned an empty response."]
|
|
63
|
+
return [
|
|
64
|
+
normalized[index : index + MAX_TELEGRAM_MESSAGE_CHARS]
|
|
65
|
+
for index in range(0, len(normalized), MAX_TELEGRAM_MESSAGE_CHARS)
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _slug(value: object) -> str:
|
|
70
|
+
raw = str(value)
|
|
71
|
+
slug = re.sub(r"[^A-Za-z0-9_.-]+", "-", raw).strip("-")
|
|
72
|
+
return slug or "unknown"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _telegram_user_name(sender: object, *, fallback: str) -> str:
|
|
76
|
+
if isinstance(sender, User):
|
|
77
|
+
parts = [
|
|
78
|
+
part.strip()
|
|
79
|
+
for part in (sender.first_name, sender.last_name)
|
|
80
|
+
if isinstance(part, str) and part.strip() != ""
|
|
81
|
+
]
|
|
82
|
+
if parts:
|
|
83
|
+
return " ".join(parts)
|
|
84
|
+
if isinstance(sender.username, str) and sender.username.strip() != "":
|
|
85
|
+
return f"@{sender.username.strip()}"
|
|
86
|
+
return fallback
|
|
87
|
+
|
|
88
|
+
if isinstance(sender, Channel):
|
|
89
|
+
if isinstance(sender.username, str) and sender.username.strip() != "":
|
|
90
|
+
return f"@{sender.username.strip()}"
|
|
91
|
+
if sender.title.strip() != "":
|
|
92
|
+
return sender.title.strip()
|
|
93
|
+
return fallback
|
|
94
|
+
|
|
95
|
+
if isinstance(sender, Chat):
|
|
96
|
+
if sender.title.strip() != "":
|
|
97
|
+
return sender.title.strip()
|
|
98
|
+
return fallback
|
|
99
|
+
|
|
100
|
+
return fallback
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class TelegramChannel(ThreadedChannel):
|
|
104
|
+
def __init__(
|
|
105
|
+
self,
|
|
106
|
+
*,
|
|
107
|
+
room: RoomClient,
|
|
108
|
+
api_id: int,
|
|
109
|
+
api_hash: str,
|
|
110
|
+
session_string: str,
|
|
111
|
+
threading_mode: str | None = None,
|
|
112
|
+
thread_dir: str | None = None,
|
|
113
|
+
thread_url_scheme: str | None = None,
|
|
114
|
+
thread_path_extension: str = ".thread",
|
|
115
|
+
thread_list_path: str | None = None,
|
|
116
|
+
llm_adapter: LLMAdapter | None = None,
|
|
117
|
+
thread_prefix: str = THREAD_PREFIX,
|
|
118
|
+
) -> None:
|
|
119
|
+
super().__init__(
|
|
120
|
+
room=room,
|
|
121
|
+
threading_mode=threading_mode,
|
|
122
|
+
thread_dir=thread_dir,
|
|
123
|
+
thread_url_scheme=thread_url_scheme,
|
|
124
|
+
thread_path_extension=thread_path_extension,
|
|
125
|
+
thread_list_path=thread_list_path,
|
|
126
|
+
llm_adapter=llm_adapter,
|
|
127
|
+
)
|
|
128
|
+
self._thread_prefix = thread_prefix.rstrip("/") or ".threads/telegram"
|
|
129
|
+
self._telegram = TelegramClient(
|
|
130
|
+
StringSession(session_string),
|
|
131
|
+
api_id,
|
|
132
|
+
api_hash,
|
|
133
|
+
)
|
|
134
|
+
self._telegram_task: asyncio.Task[Any] | None = None
|
|
135
|
+
self._pending_turns_by_message_id: dict[str, _PendingTelegramTurn] = {}
|
|
136
|
+
self._active_turns_by_turn_id: dict[str, _ActiveTelegramTurn] = {}
|
|
137
|
+
self._chat_locks: dict[str, asyncio.Lock] = {}
|
|
138
|
+
|
|
139
|
+
def _default_thread_dir_fallback_name(self) -> str:
|
|
140
|
+
return "telegram"
|
|
141
|
+
|
|
142
|
+
def handles(self, message: Message) -> bool:
|
|
143
|
+
return isinstance(
|
|
144
|
+
message.data,
|
|
145
|
+
(
|
|
146
|
+
AgentTextContentDelta,
|
|
147
|
+
ThreadCleared,
|
|
148
|
+
TurnEnded,
|
|
149
|
+
TurnStarted,
|
|
150
|
+
TurnStartRejected,
|
|
151
|
+
),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
async def on_start(self) -> None:
|
|
155
|
+
await self.publish_thread_attributes()
|
|
156
|
+
await self.open_thread_list_document()
|
|
157
|
+
await self._telegram.connect()
|
|
158
|
+
if not await self._telegram.is_user_authorized():
|
|
159
|
+
raise RuntimeError(
|
|
160
|
+
"TELEGRAM_SESSION_STRING is not authorized. "
|
|
161
|
+
"Run scripts/create-session.sh again."
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
self._telegram.add_event_handler(
|
|
165
|
+
self._handle_telegram_message,
|
|
166
|
+
events.NewMessage(incoming=True),
|
|
167
|
+
)
|
|
168
|
+
self._telegram_task = asyncio.create_task(
|
|
169
|
+
self._telegram.run_until_disconnected()
|
|
170
|
+
)
|
|
171
|
+
self._telegram_task.add_done_callback(self._log_telegram_task_failure)
|
|
172
|
+
|
|
173
|
+
me = await self._telegram.get_me()
|
|
174
|
+
if not isinstance(me, User):
|
|
175
|
+
raise RuntimeError("Telegram returned an unexpected current-user response.")
|
|
176
|
+
username = me.username or str(me.id)
|
|
177
|
+
logger.info("telegram_channel_connected username=%s", username)
|
|
178
|
+
|
|
179
|
+
async def on_stop(self) -> None:
|
|
180
|
+
self._telegram.remove_event_handler(self._handle_telegram_message)
|
|
181
|
+
telegram_task = self._telegram_task
|
|
182
|
+
self._telegram_task = None
|
|
183
|
+
if telegram_task is not None:
|
|
184
|
+
telegram_task.cancel()
|
|
185
|
+
await asyncio.gather(telegram_task, return_exceptions=True)
|
|
186
|
+
await self._telegram.disconnect()
|
|
187
|
+
await self._cancel_thread_list_background_tasks()
|
|
188
|
+
await self.close_thread_list_document()
|
|
189
|
+
for pending in self._pending_turns_by_message_id.values():
|
|
190
|
+
if not pending.response.done():
|
|
191
|
+
pending.response.cancel()
|
|
192
|
+
for active in self._active_turns_by_turn_id.values():
|
|
193
|
+
if not active.response.done():
|
|
194
|
+
active.response.cancel()
|
|
195
|
+
self._pending_turns_by_message_id.clear()
|
|
196
|
+
self._active_turns_by_turn_id.clear()
|
|
197
|
+
|
|
198
|
+
async def on_message(self, message: Message) -> None:
|
|
199
|
+
data = message.data
|
|
200
|
+
if isinstance(data, TurnStarted):
|
|
201
|
+
pending = self._pending_turns_by_message_id.pop(
|
|
202
|
+
data.source_message_id,
|
|
203
|
+
None,
|
|
204
|
+
)
|
|
205
|
+
if pending is None:
|
|
206
|
+
return
|
|
207
|
+
self._active_turns_by_turn_id[data.turn_id] = _ActiveTelegramTurn(
|
|
208
|
+
chat_id=pending.chat_id,
|
|
209
|
+
response=pending.response,
|
|
210
|
+
)
|
|
211
|
+
return
|
|
212
|
+
|
|
213
|
+
if isinstance(data, TurnStartRejected):
|
|
214
|
+
pending = self._pending_turns_by_message_id.pop(
|
|
215
|
+
data.source_message_id,
|
|
216
|
+
None,
|
|
217
|
+
)
|
|
218
|
+
if pending is None or pending.response.done():
|
|
219
|
+
return
|
|
220
|
+
pending.response.set_result(data.error.message)
|
|
221
|
+
return
|
|
222
|
+
|
|
223
|
+
if isinstance(data, AgentTextContentDelta):
|
|
224
|
+
active = self._active_turns_by_turn_id.get(data.turn_id)
|
|
225
|
+
if active is None:
|
|
226
|
+
return
|
|
227
|
+
active.text_parts.append(data.text)
|
|
228
|
+
return
|
|
229
|
+
|
|
230
|
+
if isinstance(data, ThreadCleared):
|
|
231
|
+
self._clear_thread_state(thread_id=data.thread_id)
|
|
232
|
+
return
|
|
233
|
+
|
|
234
|
+
if not isinstance(data, TurnEnded):
|
|
235
|
+
return
|
|
236
|
+
|
|
237
|
+
active = self._active_turns_by_turn_id.pop(data.turn_id, None)
|
|
238
|
+
if active is None or active.response.done():
|
|
239
|
+
return
|
|
240
|
+
if data.error is not None:
|
|
241
|
+
active.response.set_result(data.error.message)
|
|
242
|
+
return
|
|
243
|
+
active.response.set_result("".join(active.text_parts).strip())
|
|
244
|
+
|
|
245
|
+
async def _handle_telegram_message(self, event: Any) -> None:
|
|
246
|
+
text = (event.raw_text or "").strip()
|
|
247
|
+
if text == "":
|
|
248
|
+
return
|
|
249
|
+
|
|
250
|
+
chat_id = event.chat_id or event.sender_id or "unknown"
|
|
251
|
+
lock = self._chat_locks.setdefault(str(chat_id), asyncio.Lock())
|
|
252
|
+
async with lock:
|
|
253
|
+
response_text = await self._send_telegram_turn(event=event, text=text)
|
|
254
|
+
|
|
255
|
+
for chunk in telegram_chunks(response_text):
|
|
256
|
+
await event.respond(chunk)
|
|
257
|
+
|
|
258
|
+
async def _send_telegram_turn(self, *, event: Any, text: str) -> str:
|
|
259
|
+
chat_id = event.chat_id or event.sender_id or "unknown"
|
|
260
|
+
sender = await event.get_sender()
|
|
261
|
+
fallback_name = f"telegram-{event.sender_id or chat_id}"
|
|
262
|
+
participant_name = _telegram_user_name(sender, fallback=fallback_name)
|
|
263
|
+
participant_key = event.sender_id or uuid.uuid5(
|
|
264
|
+
uuid.NAMESPACE_URL, str(chat_id)
|
|
265
|
+
)
|
|
266
|
+
participant = Participant(
|
|
267
|
+
id=f"telegram:{participant_key}",
|
|
268
|
+
attributes={"name": participant_name, "role": "user"},
|
|
269
|
+
)
|
|
270
|
+
thread_id = self._thread_id_for_chat(chat_id)
|
|
271
|
+
self.bump_thread(path=thread_id, name=participant_name)
|
|
272
|
+
|
|
273
|
+
response: asyncio.Future[str] = asyncio.get_running_loop().create_future()
|
|
274
|
+
turn_start = TurnStart(
|
|
275
|
+
type=AGENT_MESSAGE_TURN_START,
|
|
276
|
+
thread_id=thread_id,
|
|
277
|
+
content=[AgentTextContent(type="text", text=text)],
|
|
278
|
+
)
|
|
279
|
+
self._pending_turns_by_message_id[turn_start.message_id] = _PendingTelegramTurn(
|
|
280
|
+
chat_id=chat_id, response=response
|
|
281
|
+
)
|
|
282
|
+
self.emit(sender=participant, payload=turn_start)
|
|
283
|
+
|
|
284
|
+
try:
|
|
285
|
+
return await asyncio.wait_for(response, timeout=RESPONSE_TIMEOUT_SECONDS)
|
|
286
|
+
except asyncio.TimeoutError:
|
|
287
|
+
self._clear_pending_response(response=response)
|
|
288
|
+
logger.warning("telegram_turn_response_timed_out chat_id=%s", chat_id)
|
|
289
|
+
return (
|
|
290
|
+
"The room agent did not answer before the Telegram channel timed out."
|
|
291
|
+
)
|
|
292
|
+
except Exception:
|
|
293
|
+
self._clear_pending_response(response=response)
|
|
294
|
+
logger.exception("telegram_turn_failed chat_id=%s", chat_id)
|
|
295
|
+
return "The room agent could not answer that message."
|
|
296
|
+
|
|
297
|
+
def _thread_id_for_chat(self, chat_id: object) -> str:
|
|
298
|
+
path = f"{self._thread_prefix}/{_slug(chat_id)}.thread"
|
|
299
|
+
if "://" in path:
|
|
300
|
+
return path
|
|
301
|
+
return self._thread_url_for_path(path=path)
|
|
302
|
+
|
|
303
|
+
def _clear_thread_state(self, *, thread_id: str) -> None:
|
|
304
|
+
pending_message_ids = [
|
|
305
|
+
message_id
|
|
306
|
+
for message_id, pending in self._pending_turns_by_message_id.items()
|
|
307
|
+
if self._thread_id_for_chat(pending.chat_id) == thread_id
|
|
308
|
+
]
|
|
309
|
+
for message_id in pending_message_ids:
|
|
310
|
+
pending = self._pending_turns_by_message_id.pop(message_id)
|
|
311
|
+
if not pending.response.done():
|
|
312
|
+
pending.response.cancel()
|
|
313
|
+
|
|
314
|
+
active_turn_ids = [
|
|
315
|
+
turn_id
|
|
316
|
+
for turn_id, active in self._active_turns_by_turn_id.items()
|
|
317
|
+
if self._thread_id_for_chat(active.chat_id) == thread_id
|
|
318
|
+
]
|
|
319
|
+
for turn_id in active_turn_ids:
|
|
320
|
+
active = self._active_turns_by_turn_id.pop(turn_id)
|
|
321
|
+
if not active.response.done():
|
|
322
|
+
active.response.cancel()
|
|
323
|
+
|
|
324
|
+
def _clear_pending_response(self, *, response: asyncio.Future[str]) -> None:
|
|
325
|
+
for message_id, pending in list(self._pending_turns_by_message_id.items()):
|
|
326
|
+
if pending.response is response:
|
|
327
|
+
self._pending_turns_by_message_id.pop(message_id, None)
|
|
328
|
+
for turn_id, active in list(self._active_turns_by_turn_id.items()):
|
|
329
|
+
if active.response is response:
|
|
330
|
+
self._active_turns_by_turn_id.pop(turn_id, None)
|
|
331
|
+
|
|
332
|
+
@staticmethod
|
|
333
|
+
def _log_telegram_task_failure(task: asyncio.Task[Any]) -> None:
|
|
334
|
+
if task.cancelled():
|
|
335
|
+
return
|
|
336
|
+
exc = task.exception()
|
|
337
|
+
if exc is not None:
|
|
338
|
+
logger.error("telegram_channel_disconnected", exc_info=exc)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def create_channel(
|
|
342
|
+
*,
|
|
343
|
+
room: RoomClient,
|
|
344
|
+
threading_mode: str | None = None,
|
|
345
|
+
thread_dir: str | None = None,
|
|
346
|
+
thread_url_scheme: str | None = None,
|
|
347
|
+
thread_path_extension: str = ".thread",
|
|
348
|
+
thread_list_path: str | None = None,
|
|
349
|
+
llm_adapter: LLMAdapter | None = None,
|
|
350
|
+
) -> TelegramChannel:
|
|
351
|
+
return TelegramChannel(
|
|
352
|
+
room=room,
|
|
353
|
+
api_id=int(required_env("TELEGRAM_API_ID")),
|
|
354
|
+
api_hash=required_env("TELEGRAM_API_HASH"),
|
|
355
|
+
session_string=required_env("TELEGRAM_SESSION_STRING"),
|
|
356
|
+
threading_mode=threading_mode,
|
|
357
|
+
thread_dir=thread_dir,
|
|
358
|
+
thread_url_scheme=thread_url_scheme,
|
|
359
|
+
thread_path_extension=thread_path_extension,
|
|
360
|
+
thread_list_path=thread_list_path,
|
|
361
|
+
llm_adapter=llm_adapter,
|
|
362
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.44.11"
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: meshagent-telegram
|
|
3
|
+
Version: 0.44.11
|
|
4
|
+
Summary: Telegram channel support for MeshAgent
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Documentation, https://docs.meshagent.com
|
|
7
|
+
Project-URL: Website, https://www.meshagent.com
|
|
8
|
+
Project-URL: Source, https://www.meshagent.com
|
|
9
|
+
Requires-Python: >=3.13
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: meshagent-api==0.44.11
|
|
13
|
+
Requires-Dist: meshagent-agents==0.44.11
|
|
14
|
+
Requires-Dist: telethon<2,>=1.36
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# MeshAgent Telegram
|
|
18
|
+
|
|
19
|
+
Telegram account channel support for MeshAgent process agents.
|
|
20
|
+
|
|
21
|
+
This package exports `TelegramChannel` and `create_channel(...)` for use with a
|
|
22
|
+
MeshAgent process channel shim.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
CHANGELOG.md
|
|
2
|
+
LICENSE
|
|
3
|
+
MANIFEST.in
|
|
4
|
+
README.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
meshagent/telegram/__init__.py
|
|
7
|
+
meshagent/telegram/channel.py
|
|
8
|
+
meshagent/telegram/version.py
|
|
9
|
+
meshagent_telegram.egg-info/PKG-INFO
|
|
10
|
+
meshagent_telegram.egg-info/SOURCES.txt
|
|
11
|
+
meshagent_telegram.egg-info/dependency_links.txt
|
|
12
|
+
meshagent_telegram.egg-info/requires.txt
|
|
13
|
+
meshagent_telegram.egg-info/top_level.txt
|
|
14
|
+
tests/test_telegram_channel.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
meshagent
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "meshagent-telegram"
|
|
7
|
+
description = "Telegram channel support for MeshAgent"
|
|
8
|
+
dynamic = ["version", "readme"]
|
|
9
|
+
requires-python = ">=3.13"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"meshagent-api==0.44.11",
|
|
13
|
+
"meshagent-agents==0.44.11",
|
|
14
|
+
"telethon>=1.36,<2",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Documentation = "https://docs.meshagent.com"
|
|
19
|
+
Website = "https://www.meshagent.com"
|
|
20
|
+
Source = "https://www.meshagent.com"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
include = ["meshagent.*"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.package-data]
|
|
26
|
+
"meshagent.telegram" = ["py.typed", "*.pyi", "**/*.pyi", "**/*.js"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.dynamic]
|
|
29
|
+
version = {attr = "meshagent.telegram.version.__version__"}
|
|
30
|
+
readme = { file = "README.md", content-type = "text/markdown" }
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
from unittest import SkipTest
|
|
5
|
+
|
|
6
|
+
if importlib.util.find_spec("telethon") is None:
|
|
7
|
+
raise SkipTest("telethon is required for meshagent-telegram channel tests")
|
|
8
|
+
|
|
9
|
+
import meshagent.telegram as telegram
|
|
10
|
+
from meshagent.telegram.channel import TelegramChannel, create_channel, telegram_chunks
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_package_exports_channel_factory() -> None:
|
|
14
|
+
assert telegram.TelegramChannel is TelegramChannel
|
|
15
|
+
assert telegram.create_channel is create_channel
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_telegram_chunks_empty_response() -> None:
|
|
19
|
+
assert telegram_chunks(" ") == ["The room agent returned an empty response."]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_telegram_chunks_long_response() -> None:
|
|
23
|
+
chunks = telegram_chunks("x" * 3901)
|
|
24
|
+
|
|
25
|
+
assert chunks == ["x" * 3900, "x"]
|