File size: 50,299 Bytes
5374a2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 |
"""
Telegram API Tool for EvoAgentX
This module provides comprehensive Telegram integration including:
- Message retrieval and search
- Sending messages and scheduling
- Chat management and file operations
Compatible with EvoAgentX tool architecture and follows the latest Telegram API patterns.
"""
import os
import asyncio
import time
from typing import Dict, Any, List
from telethon import TelegramClient
from telethon.tl.types import Message, User, Chat, Channel
from telethon.errors import (
FloodWaitError,
ChatAdminRequiredError,
UserBannedInChannelError,
ChannelPrivateError,
UserNotParticipantError,
ChatWriteForbiddenError,
MessageEmptyError,
MessageTooLongError
)
from dotenv import load_dotenv
import PyPDF2
from .tool import Tool, Toolkit
from ..core.module import BaseModule
from ..core.logging import logger
# Load environment variables
load_dotenv()
# Global constants
SESSION_NAME = 'ai_agent_session'
class TelegramBase(BaseModule):
"""
Base class for Telegram API interactions.
Handles client management, authentication, and common utilities.
"""
def __init__(self, api_id: str = None, api_hash: str = None, phone: str = None, **kwargs):
"""
Initialize the Telegram base.
Args:
api_id (str, optional): Telegram API ID. If not provided, will try to get from TELEGRAM_API_ID environment variable.
api_hash (str, optional): Telegram API Hash. If not provided, will try to get from TELEGRAM_API_HASH environment variable.
phone (str, optional): Phone number for authentication. If not provided, will try to get from TELEGRAM_PHONE environment variable.
**kwargs: Additional keyword arguments for parent class
"""
super().__init__(**kwargs)
# Get credentials from parameters or environment variables
self.api_id = api_id or os.getenv("TELEGRAM_API_ID")
self.api_hash = api_hash or os.getenv("TELEGRAM_API_HASH")
self.phone = phone or os.getenv("TELEGRAM_PHONE")
if not self.api_id or not self.api_hash:
logger.warning(
"No Telegram API credentials provided. Please set TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables "
"or pass api_id and api_hash parameters. Get your credentials from: https://my.telegram.org/apps"
)
def _get_client(self) -> TelegramClient:
"""
Create and return a Telegram client instance.
Returns:
TelegramClient: Configured Telegram client
"""
if not self.api_id or not self.api_hash:
raise ValueError("Telegram API credentials not found. Please set TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables.")
client = TelegramClient(SESSION_NAME, self.api_id, self.api_hash)
return client
def _format_message(self, message: Message) -> Dict[str, Any]:
"""
Format a Telegram message for consistent output.
Args:
message: Telegram message object
Returns:
dict: Formatted message data
"""
return {
"id": message.id,
"text": message.text or "",
"date": message.date.isoformat() if message.date else None,
"sender_id": message.sender_id,
"chat_id": message.chat_id,
"is_reply": message.reply_to_msg_id is not None,
"reply_to_msg_id": message.reply_to_msg_id,
"has_media": message.media is not None,
"media_type": type(message.media).__name__ if message.media else None
}
def _format_chat(self, chat) -> Dict[str, Any]:
"""
Format a Telegram chat for consistent output.
Args:
chat: Telegram chat object
Returns:
dict: Formatted chat data
"""
chat_type = "unknown"
title = "Unknown"
if isinstance(chat, User):
chat_type = "user"
title = f"{chat.first_name or ''} {chat.last_name or ''}".strip() or chat.username or "Unknown User"
elif isinstance(chat, Chat):
chat_type = "group"
title = chat.title or "Unknown Group"
elif isinstance(chat, Channel):
chat_type = "channel" if chat.broadcast else "supergroup"
title = chat.title or "Unknown Channel"
return {
"id": chat.id,
"title": title,
"type": chat_type,
"username": getattr(chat, 'username', None)
}
def _run_async(self, coro):
"""
Run an async coroutine, handling both sync and async contexts.
Args:
coro: Async coroutine to run
Returns:
Result of the coroutine
"""
try:
try:
asyncio.get_running_loop()
# We're in an async context, need to run in a new thread
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(asyncio.run, coro)
return future.result()
except RuntimeError:
# No running loop, we can use asyncio.run
return asyncio.run(coro)
except Exception as e:
return {
"success": False,
"error": f"Failed to execute async operation: {str(e)}"
}
class FetchLatestMessagesTool(Tool):
"""Retrieve the most recent messages from a specific Telegram contact by their name."""
name: str = "fetch_latest_messages"
description: str = "Retrieve the most recent messages from a specific Telegram contact by their name. If multiple contacts match the name, it will ask for clarification."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to fetch messages from (e.g., 'Shivam Kumar')"
},
"limit": {
"type": "integer",
"description": "Maximum number of messages to retrieve (default: 10)"
}
}
required: List[str] = ["contact_name"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, limit: int = 10) -> Dict[str, Any]:
"""
Fetch the latest messages from a Telegram contact by their name.
Args:
contact_name: The name of the Telegram contact
limit: Maximum number of messages to retrieve
Returns:
Dictionary with message results
"""
async def _fetch_messages():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name (users, groups, and channels)
matches = []
async for dialog in client.iter_dialogs():
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id, "chat": dialog.entity})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
# Format the list of matches for the user to choose from
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# If we reach here, we have exactly one match
chat = matches[0]['chat']
# Fetch messages
messages = []
async for message in client.iter_messages(chat, limit=limit):
messages.append(self.telegram_base._format_message(message))
# Format chat info
chat_info = self.telegram_base._format_chat(chat)
return {
"success": True,
"chat": chat_info,
"messages_count": len(messages),
"messages": messages
}
except FloodWaitError as e:
return {
"success": False,
"error": f"Rate limited. Please wait {e.seconds} seconds before trying again."
}
except (ChatAdminRequiredError, UserBannedInChannelError, ChannelPrivateError,
UserNotParticipantError, ChatWriteForbiddenError) as e:
return {
"success": False,
"error": f"Access denied: {str(e)}"
}
except Exception as e:
logger.error(f"Error fetching messages: {str(e)}")
return {
"success": False,
"error": f"Failed to fetch messages: {str(e)}"
}
finally:
if client:
await client.disconnect()
# Run the async function
return self.telegram_base._run_async(_fetch_messages())
class SearchMessagesByKeywordTool(Tool):
"""Find specific information by searching for a keyword within a contact's chat history."""
name: str = "search_messages_by_keyword"
description: str = "Find specific information by searching for a keyword within a contact's chat history. If multiple contacts match the name, it will ask for clarification."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to search messages from (e.g., 'Shivam Kumar')"
},
"keyword": {
"type": "string",
"description": "Keyword or phrase to search for in messages"
},
"limit": {
"type": "integer",
"description": "Maximum number of matching messages to retrieve (default: 10)"
}
}
required: List[str] = ["contact_name", "keyword"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, keyword: str, limit: int = 10) -> Dict[str, Any]:
"""
Search for messages containing a specific keyword in a contact's chat.
Args:
contact_name: The name of the Telegram contact
keyword: Keyword to search for
limit: Maximum number of matching messages to retrieve
Returns:
Dictionary with search results
"""
async def _search_messages():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name (users, groups, and channels)
matches = []
async for dialog in client.iter_dialogs():
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id, "chat": dialog.entity})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
# Format the list of matches for the user to choose from
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# If we reach here, we have exactly one match
chat = matches[0]['chat']
# Search messages
messages = []
async for message in client.iter_messages(chat, search=keyword, limit=limit):
if message.text and keyword.lower() in message.text.lower():
messages.append(self.telegram_base._format_message(message))
# Format chat info
chat_info = self.telegram_base._format_chat(chat)
return {
"success": True,
"chat": chat_info,
"keyword": keyword,
"matches_count": len(messages),
"messages": messages
}
except FloodWaitError as e:
return {
"success": False,
"error": f"Rate limited. Please wait {e.seconds} seconds before trying again."
}
except (ChatAdminRequiredError, UserBannedInChannelError, ChannelPrivateError,
UserNotParticipantError, ChatWriteForbiddenError) as e:
return {
"success": False,
"error": f"Access denied: {str(e)}"
}
except Exception as e:
logger.error(f"Error searching messages: {str(e)}")
return {
"success": False,
"error": f"Failed to search messages: {str(e)}"
}
finally:
if client:
await client.disconnect()
# Run the async function
return self.telegram_base._run_async(_search_messages())
class SendMessageTool(Tool):
"""Send a text message to a Telegram contact by their name."""
# --- MODIFIED TOOL DEFINITION ---
name: str = "send_message_by_name"
description: str = (
"Finds a contact by their name and sends them a text message. "
"If multiple contacts match the name, it will ask for clarification."
)
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to search for (e.g., 'Shivam Kumar')"
},
"message_text": {
"type": "string",
"description": "The text message to send"
}
}
required: List[str] = ["contact_name", "message_text"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
# --- MODIFIED CALL SIGNATURE ---
def __call__(self, contact_name: str, message_text: str) -> Dict[str, Any]:
"""
Finds a contact by name and sends them a message.
Args:
contact_name: The name of the Telegram contact.
message_text: Text message to send.
Returns:
Dictionary with the send result or a request for clarification.
"""
async def _send_message_by_name():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# --- NEW LOGIC START: Find Contact by Name ---
matches = []
async for dialog in client.iter_dialogs():
if dialog.is_user and not dialog.entity.bot:
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
# Format the list of matches for the user to choose from
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# If we reach here, we have exactly one match.
chat_id = matches[0]['id']
# --- NEW LOGIC END ---
# Send message using the resolved chat_id
sent_message = await client.send_message(chat_id, message_text)
# Get entity for formatting the response
chat = await client.get_entity(chat_id)
chat_info = self.telegram_base._format_chat(chat)
return {
"success": True,
"message_id": sent_message.id,
"chat": chat_info,
"message_text": message_text,
"sent_at": sent_message.date.isoformat() if sent_message.date else None
}
# --- REUSED EXISTING ERROR HANDLING ---
except FloodWaitError as e:
return {"success": False, "error": f"Rate limited. Please wait {e.seconds} seconds."}
except (ChatAdminRequiredError, UserBannedInChannelError, ChannelPrivateError,
UserNotParticipantError, ChatWriteForbiddenError) as e:
return {"success": False, "error": f"Access denied: {str(e)}"}
except MessageEmptyError:
return {"success": False, "error": "Message is empty."}
except MessageTooLongError:
return {"success": False, "error": "Message is too long."}
except Exception as e:
logger.error(f"Error sending message: {str(e)}")
return {"success": False, "error": f"Failed to send message: {str(e)}"}
finally:
if client:
await client.disconnect()
return self.telegram_base._run_async(_send_message_by_name())
class ListRecentChatsTool(Tool):
"""Get a list of recent conversations, allowing the agent to ask for clarification if a user's request is ambiguous."""
name: str = "list_recent_chats"
description: str = "Get a list of recent conversations, allowing the agent to ask for clarification if a user's request is ambiguous (e.g., 'Summarize my last chat')."
inputs: Dict[str, Dict[str, str]] = {
"limit": {
"type": "integer",
"description": "Maximum number of recent chats to retrieve (default: 10)"
}
}
required: List[str] = []
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, limit: int = 10) -> Dict[str, Any]:
"""
List recent Telegram chats.
Args:
limit: Maximum number of recent chats to retrieve
Returns:
Dictionary with chat list
"""
async def _list_chats():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Get recent dialogs
dialogs = []
async for dialog in client.iter_dialogs(limit=limit):
chat_info = self.telegram_base._format_chat(dialog.entity)
dialogs.append({
**chat_info,
"last_message_date": dialog.date.isoformat() if dialog.date else None,
"unread_count": dialog.unread_count
})
return {
"success": True,
"chats_count": len(dialogs),
"chats": dialogs
}
except Exception as e:
logger.error(f"Error listing chats: {str(e)}")
return {
"success": False,
"error": f"Failed to list chats: {str(e)}"
}
finally:
if client:
await client.disconnect()
# Run the async function
return self.telegram_base._run_async(_list_chats())
class FindAndRetrieveFileTool(Tool):
"""Locate a specific file within a contact's chat based on a search query. This tool should return metadata about the file (name, size, type), not download its contents."""
name: str = "find_and_retrieve_file"
description: str = "Locate a specific file within a contact's chat based on a search query. This tool should return metadata about the file (name, size, type), not download its contents. If multiple contacts match the name, it will ask for clarification."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to search files from (e.g., 'Shivam Kumar')"
},
"filename_query": {
"type": "string",
"description": "Filename or search query to find files"
}
}
required: List[str] = ["contact_name", "filename_query"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, filename_query: str) -> Dict[str, Any]:
"""
Find files in a Telegram contact's chat based on filename query.
Args:
contact_name: The name of the Telegram contact
filename_query: Filename or search query to find files
Returns:
Dictionary with file search results
"""
async def _find_files():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name (users, groups, and channels)
matches = []
async for dialog in client.iter_dialogs():
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id, "chat": dialog.entity})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
# Format the list of matches for the user to choose from
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# If we reach here, we have exactly one match
chat = matches[0]['chat']
# Search for files using the working Telethon approach
files = []
message_count = 0
async for message in client.iter_messages(chat):
message_count += 1
if message.document:
# Get file information using the working approach
doc = message.document
filename = "Unknown"
# Extract filename from attributes (working approach)
for attribute in doc.attributes:
if hasattr(attribute, 'file_name'):
filename = attribute.file_name
break
# Check if filename matches query (case-insensitive)
if not filename_query or filename_query.lower() in filename.lower():
files.append({
"message_id": message.id,
"filename": filename,
"file_size": doc.size,
"mime_type": doc.mime_type,
"date": message.date.isoformat() if message.date else None,
"sender_id": message.sender_id,
"caption": message.text or ""
})
# Limit search to prevent infinite loops (increased from 100 to 1000)
if message_count > 1000:
break
# Format chat info
chat_info = self.telegram_base._format_chat(chat)
return {
"success": True,
"chat": chat_info,
"query": filename_query,
"files_found": len(files),
"files": files
}
except FloodWaitError as e:
return {
"success": False,
"error": f"Rate limited. Please wait {e.seconds} seconds before trying again."
}
except (ChatAdminRequiredError, UserBannedInChannelError, ChannelPrivateError,
UserNotParticipantError, ChatWriteForbiddenError) as e:
return {
"success": False,
"error": f"Access denied: {str(e)}"
}
except Exception as e:
logger.error(f"Error finding files: {str(e)}")
return {
"success": False,
"error": f"Failed to find files: {str(e)}"
}
finally:
if client:
await client.disconnect()
# Run the async function
return self.telegram_base._run_async(_find_files())
class SummarizeContactMessagesTool(Tool):
"""Summarize recent messages from a specific Telegram contact by their name."""
name: str = "summarize_contact_messages"
description: str = "Summarize recent messages from a specific Telegram contact by their name. Provides a summary of the conversation history."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to summarize messages for (e.g., 'Shivam Kumar')"
},
"limit": {
"type": "integer",
"description": "Maximum number of recent messages to analyze for summarization (default: 20)"
}
}
required: List[str] = ["contact_name"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, limit: int = 20) -> Dict[str, Any]:
"""
Summarize recent messages from a contact by name.
Args:
contact_name: The name of the Telegram contact
limit: Maximum number of recent messages to analyze
Returns:
Dictionary with summarization results
"""
async def _summarize_messages():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name (same logic as send_message_by_name)
matches = []
async for dialog in client.iter_dialogs():
if dialog.is_user and not dialog.entity.bot:
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
# Format the list of matches for the user to choose from
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# If we reach here, we have exactly one match.
chat_id = matches[0]['id']
# Get chat entity for formatting
chat = await client.get_entity(chat_id)
chat_info = self.telegram_base._format_chat(chat)
# Fetch recent messages
messages = []
async for message in client.iter_messages(chat, limit=limit):
if message.text: # Only include text messages
messages.append({
"id": message.id,
"text": message.text,
"date": message.date.isoformat() if message.date else None,
"sender_id": message.sender_id,
"is_outgoing": message.out
})
# Create a simple summary
if not messages:
summary = f"No recent text messages found with {contact_name}."
else:
# Basic summarization logic
total_messages = len(messages)
outgoing_count = sum(1 for msg in messages if msg['is_outgoing'])
incoming_count = total_messages - outgoing_count
# Get date range
dates = [msg['date'] for msg in messages if msg['date']]
if dates:
latest_date = max(dates)
earliest_date = min(dates)
else:
latest_date = earliest_date = "Unknown"
# Extract key topics (simple keyword extraction)
all_text = " ".join([msg['text'] for msg in messages])
words = all_text.lower().split()
word_freq = {}
for word in words:
if len(word) > 3: # Only words longer than 3 characters
word_freq[word] = word_freq.get(word, 0) + 1
# Get top 5 most frequent words
top_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5]
summary = f"""Conversation Summary with {contact_name}:
• Total messages analyzed: {total_messages}
• Messages from you: {outgoing_count}
• Messages from {contact_name}: {incoming_count}
• Date range: {earliest_date} to {latest_date}
• Key topics: {', '.join([word for word, freq in top_words])}
• Recent activity: {'Active' if total_messages > 0 else 'No recent messages'}"""
return {
"success": True,
"contact": chat_info,
"messages_analyzed": len(messages),
"summary": summary,
"recent_messages": messages[:5] # Show first 5 messages as examples
}
except Exception as e:
logger.error(f"Error summarizing messages: {str(e)}")
return {
"success": False,
"error": f"Failed to summarize messages: {str(e)}"
}
finally:
if client:
await client.disconnect()
# Run the async function
return self.telegram_base._run_async(_summarize_messages())
class DownloadFileTool(Tool):
"""Download a file from a Telegram contact by their name."""
name: str = "download_file"
description: str = "Download a file from a Telegram contact by their name. Downloads the file to a local directory."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to download file from (e.g., 'Vinay Kumar')"
},
"filename_query": {
"type": "string",
"description": "Filename or search query to find the file (e.g., 'Kafka.pdf')"
},
"download_dir": {
"type": "string",
"description": "Directory to download the file to (default: 'downloads')"
}
}
required: List[str] = ["contact_name", "filename_query"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, filename_query: str, download_dir: str = "downloads") -> Dict[str, Any]:
"""
Download a file from a Telegram contact.
Args:
contact_name: The name of the Telegram contact
filename_query: Filename or search query to find the file
download_dir: Directory to download the file to
Returns:
Dictionary with download result
"""
async def _download_file():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name
matches = []
async for dialog in client.iter_dialogs():
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id, "chat": dialog.entity})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# Get the contact
chat = matches[0]['chat']
# Search for the file
found_message = None
message_count = 0
async for message in client.iter_messages(chat):
message_count += 1
if message.document:
doc = message.document
filename = "Unknown"
# Extract filename from attributes
for attribute in doc.attributes:
if hasattr(attribute, 'file_name'):
filename = attribute.file_name
break
# Check if filename matches query
if filename_query.lower() in filename.lower():
found_message = message
break
if message_count > 1000:
break
if not found_message:
return {
"success": False,
"error": f"File '{filename_query}' not found in contact '{contact_name}'"
}
# Download the file
if not os.path.exists(download_dir):
os.makedirs(download_dir)
downloaded_path = await client.download_media(
found_message,
file=os.path.join(download_dir, filename)
)
if downloaded_path:
file_size = os.path.getsize(downloaded_path)
return {
"success": True,
"message": "File downloaded successfully",
"filename": filename,
"file_path": downloaded_path,
"file_size": file_size,
"download_dir": download_dir,
"contact_name": contact_name
}
else:
return {
"success": False,
"error": "File download failed"
}
except Exception as e:
return {
"success": False,
"error": f"Failed to download file: {str(e)}"
}
finally:
if client:
await client.disconnect()
return self.telegram_base._run_async(_download_file())
class ReadFileContentTool(Tool):
"""Read the content of a file from a Telegram contact by their name."""
name: str = "read_file_content"
description: str = "Read the content of a file from a Telegram contact by their name. Downloads the file and extracts its text content."
inputs: Dict[str, Dict[str, str]] = {
"contact_name": {
"type": "string",
"description": "The name of the contact to read file from (e.g., 'Vinay Kumar')"
},
"filename_query": {
"type": "string",
"description": "Filename or search query to find the file (e.g., 'Kafka.pdf')"
},
"content_type": {
"type": "string",
"description": "Type of content to extract: 'full', 'first_lines', 'last_lines', 'summary' (default: 'full')"
},
"lines_count": {
"type": "integer",
"description": "Number of lines to extract for first_lines/last_lines (default: 3)"
}
}
required: List[str] = ["contact_name", "filename_query"]
def __init__(self, telegram_base: TelegramBase):
super().__init__()
self.telegram_base = telegram_base
def __call__(self, contact_name: str, filename_query: str, content_type: str = "full", lines_count: int = 3) -> Dict[str, Any]:
"""
Read the content of a file from a Telegram contact.
Args:
contact_name: The name of the Telegram contact
filename_query: Filename or search query to find the file
content_type: Type of content to extract
lines_count: Number of lines for first_lines/last_lines
Returns:
Dictionary with file content
"""
async def _read_file_content():
client = None
try:
client = self.telegram_base._get_client()
await client.start(phone=self.telegram_base.phone)
# Find contact by name
matches = []
async for dialog in client.iter_dialogs():
if contact_name.lower() in dialog.name.lower():
matches.append({"name": dialog.name, "id": dialog.id, "chat": dialog.entity})
if len(matches) == 0:
return {
"success": False,
"error": f"Contact '{contact_name}' not found. Please check the name."
}
if len(matches) > 1:
clarification_list = [f"{m['name']} (ID: {m['id']})" for m in matches]
return {
"success": False,
"error": "Ambiguous contact name. Please clarify which user you mean.",
"clarification_needed": clarification_list
}
# Get the contact
chat = matches[0]['chat']
# Search for the file
found_message = None
message_count = 0
async for message in client.iter_messages(chat):
message_count += 1
if message.document:
doc = message.document
filename = "Unknown"
# Extract filename from attributes
for attribute in doc.attributes:
if hasattr(attribute, 'file_name'):
filename = attribute.file_name
break
# Check if filename matches query
if filename_query.lower() in filename.lower():
found_message = message
break
if message_count > 1000:
break
if not found_message:
return {
"success": False,
"error": f"File '{filename_query}' not found in contact '{contact_name}'"
}
# Download the file temporarily with unique filename
temp_dir = "temp_downloads"
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
# Create unique filename to avoid conflicts
unique_filename = f"{int(time.time())}_{filename}"
downloaded_path = await client.download_media(
found_message,
file=os.path.join(temp_dir, unique_filename)
)
if not downloaded_path:
return {
"success": False,
"error": "Failed to download file for reading"
}
# Read file content based on type
try:
if filename.lower().endswith('.pdf'):
# Read PDF content
with open(downloaded_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
# Extract text from all pages
full_text = ""
for page in pdf_reader.pages:
full_text += page.extract_text() + "\n"
# Process content based on type
lines = [line.strip() for line in full_text.split('\n') if line.strip()]
if content_type == "full":
content = full_text
elif content_type == "first_lines":
content = "\n".join(lines[:lines_count])
elif content_type == "last_lines":
content = "\n".join(lines[-lines_count:])
elif content_type == "summary":
content = f"Document has {len(pdf_reader.pages)} pages, {len(lines)} lines, {len(full_text)} characters"
else:
content = full_text
return {
"success": True,
"message": "File content read successfully",
"filename": filename,
"content_type": content_type,
"content": content,
"file_info": {
"pages": len(pdf_reader.pages),
"lines": len(lines),
"characters": len(full_text)
},
"contact_name": contact_name
}
else:
# Read text file
with open(downloaded_path, 'r', encoding='utf-8') as file:
content = file.read()
lines = content.split('\n')
if content_type == "full":
processed_content = content
elif content_type == "first_lines":
processed_content = "\n".join(lines[:lines_count])
elif content_type == "last_lines":
processed_content = "\n".join(lines[-lines_count:])
elif content_type == "summary":
processed_content = f"File has {len(lines)} lines, {len(content)} characters"
else:
processed_content = content
return {
"success": True,
"message": "File content read successfully",
"filename": filename,
"content_type": content_type,
"content": processed_content,
"file_info": {
"lines": len(lines),
"characters": len(content)
},
"contact_name": contact_name
}
except Exception as e:
return {
"success": False,
"error": f"Failed to read file content: {str(e)}"
}
finally:
# Clean up temp file
try:
if os.path.exists(downloaded_path):
os.remove(downloaded_path)
except Exception:
pass # Ignore cleanup errors
except Exception as e:
return {
"success": False,
"error": f"Failed to read file: {str(e)}"
}
finally:
if client:
await client.disconnect()
return self.telegram_base._run_async(_read_file_content())
class TelegramToolkit(Toolkit):
"""
Complete Telegram toolkit containing all available tools.
"""
def __init__(self, api_id: str = None, api_hash: str = None, phone: str = None, name: str = "TelegramToolkit"):
"""
Initialize the Telegram toolkit.
Args:
api_id (str, optional): Telegram API ID. If not provided, will try to get from TELEGRAM_API_ID environment variable.
api_hash (str, optional): Telegram API Hash. If not provided, will try to get from TELEGRAM_API_HASH environment variable.
phone (str, optional): Phone number for authentication. If not provided, will try to get from TELEGRAM_PHONE environment variable.
name (str): Toolkit name
"""
# Create shared Telegram base instance
telegram_base = TelegramBase(api_id=api_id, api_hash=api_hash, phone=phone)
# Create all tools with shared base
tools = [
FetchLatestMessagesTool(telegram_base=telegram_base),
SearchMessagesByKeywordTool(telegram_base=telegram_base),
SendMessageTool(telegram_base=telegram_base), # This is now send_message_by_name
ListRecentChatsTool(telegram_base=telegram_base),
FindAndRetrieveFileTool(telegram_base=telegram_base),
SummarizeContactMessagesTool(telegram_base=telegram_base),
DownloadFileTool(telegram_base=telegram_base),
ReadFileContentTool(telegram_base=telegram_base)
]
# Initialize parent with tools
super().__init__(name=name, tools=tools)
# Store base instance for access
self.telegram_base = telegram_base |