Skip to content

Commit a7fd0e4

Browse files
Make Telegram optional (#501)
This PR makes the bot_token optional when using the TelegramMixin. * bot_token can be updated with the auth-protected `connect_telegram` route * bot_tokens are either passed via the internal kv store OR the config * config bot_token takes precedence over the kv-stored bot_token * Note: kv store is used since config is idempotent.
1 parent c61abce commit a7fd0e4

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

src/steamship/agents/mixins/transports/telegram.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from steamship.agents.service.agent_service import AgentService
1313
from steamship.agents.utils import with_llm
1414
from steamship.invocable import Config, InvocableResponse, InvocationContext, post
15+
from steamship.utils.kv_store import KeyValueStore
1516

1617

1718
class TelegramTransportConfig(Config):
@@ -35,12 +36,23 @@ def __init__(
3536
agent: Agent,
3637
):
3738
super().__init__(client=client)
38-
self.api_root = f"{config.api_base}{config.bot_token}"
39-
self.bot_token = config.bot_token
39+
40+
self.store = KeyValueStore(self.client, store_identifier="_telegram_config")
41+
bot_token = (self.store.get("bot_token") or {}).get("token")
42+
self.bot_token = config.bot_token or bot_token
43+
self.api_root = f"{config.api_base}{self.bot_token}"
4044
self.agent = agent
4145
self.agent_service = agent_service
4246

4347
def instance_init(self, config: Config, invocation_context: InvocationContext):
48+
if self.bot_token:
49+
self.api_root = f"{config.api_base}{config.bot_token or self.bot_token}"
50+
try:
51+
self._instance_init(config=config, invocation_context=invocation_context)
52+
except Exception: # noqa: S110
53+
pass
54+
55+
def _instance_init(self, config: Config, invocation_context: InvocationContext):
4456
webhook_url = invocation_context.invocable_url + "telegram_respond"
4557

4658
logging.info(
@@ -65,6 +77,17 @@ def instance_init(self, config: Config, invocation_context: InvocationContext):
6577
def telegram_webhook_info(self) -> dict:
6678
return requests.get(self.api_root + "/getWebhookInfo").json()
6779

80+
@post("connect_telegram")
81+
def connect_telegram(self, bot_token: str):
82+
self.store.set("bot_token", {"token": bot_token})
83+
self.bot_token = bot_token
84+
85+
try:
86+
self.instance_init(self.agent_service.config, self.agent_service.context)
87+
return "OK"
88+
except Exception as e:
89+
return f"Could not set webhook for bot. Exception: {e}"
90+
6891
@post("telegram_disconnect_webhook")
6992
def telegram_disconnect_webhook(self, *args, **kwargs):
7093
"""Unsubscribe from Telegram updates."""

0 commit comments

Comments
 (0)