(self, task, tmp_dir)
| 678 | shutil.rmtree(tmp_dir, ignore_errors=True) |
| 679 | |
| 680 | async def _scrape_telegram(self, task, tmp_dir): |
| 681 | global core |
| 682 | creds = core.creds |
| 683 | session_str = core.telegram_session() |
| 684 | if not session_str: |
| 685 | raise Exception("Non autenticato su Telegram. Inserisci le API e fai login.") |
| 686 | |
| 687 | client = TelegramClient(StringSession(session_str), int(creds['tg_id']), creds['tg_hash']) |
| 688 | await client.connect() |
| 689 | if not await client.is_user_authorized(): |
| 690 | raise Exception("Sessione Telegram non valida.") |
| 691 | |
| 692 | target = task['target'] |
| 693 | opts = task['options'] |
| 694 | tutto = opts.get('tutto', False) |
| 695 | |
| 696 | try: |
| 697 | entity = await client.get_entity(target) |
| 698 | except Exception as e: |
| 699 | raise Exception(f"Impossibile trovare il target: {e}") |
| 700 | |
| 701 | task['progress'] = 15 |
| 702 | |
| 703 | if tutto or opts.get('dati', False): |
| 704 | info = { |
| 705 | "id": entity.id, |
| 706 | "username": getattr(entity, 'username', None), |
| 707 | "title": getattr(entity, 'title', getattr(entity, 'first_name', '')), |
| 708 | "type": type(entity).__name__ |
| 709 | } |
| 710 | if isinstance(entity, types.User): |
| 711 | try: |
| 712 | full = await client(functions.users.GetFullUserRequest(entity)) |
| 713 | info["bio"] = full.full_user.about |
| 714 | except: pass |
| 715 | elif isinstance(entity, (types.Channel, types.Chat)): |
| 716 | try: |
| 717 | full = await client(functions.channels.GetFullChannelRequest(entity)) |
| 718 | info["bio"] = full.full_chat.about |
| 719 | except: pass |
| 720 | |
| 721 | with open(os.path.join(tmp_dir, "info.json"), "w", encoding="utf-8") as f: |
| 722 | safe_json_dump(info, f, indent=4, ensure_ascii=False) |
| 723 | |
| 724 | if isinstance(entity, (types.Channel, types.Chat)): |
| 725 | try: |
| 726 | chat_history = [] |
| 727 | async for msg in client.iter_messages(entity, limit=None): |
| 728 | if msg.text: |
| 729 | chat_history.append({ |
| 730 | "id": msg.id, |
| 731 | "date": str(msg.date), |
| 732 | "sender_id": msg.sender_id, |
| 733 | "text": msg.text, |
| 734 | "fwd_from": str(msg.fwd_from) if msg.fwd_from else None |
| 735 | }) |
| 736 | with open(os.path.join(tmp_dir, "chat_history.json"), "w", encoding="utf-8") as f: |
| 737 | safe_json_dump(chat_history, f, indent=4, ensure_ascii=False) |
no test coverage detected