Files changed (1) hide show
  1. app.py +0 -182
app.py DELETED
@@ -1,182 +0,0 @@
1
- import os
2
- import asyncio
3
- import logging
4
- from telethon import TelegramClient, events
5
- from telethon.sessions import StringSession
6
- import aiohttp
7
- from aiohttp import web
8
-
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
-
12
- # --- Configuration ---
13
- API_ID = 29988110
14
- API_HASH = "a524f28572523984696d1d3a95d0d6ae"
15
- # Use environment variable for session string if available, otherwise fallback to the hardcoded one
16
- SESSION_STRING = os.environ.get("SESSION_STRING")
17
-
18
- WORKER_URL = "https://aibot.aungminsan23.workers.dev/"
19
-
20
- # Initialize the Telethon client
21
- client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)
22
-
23
- async def forward_to_worker(payload: dict):
24
- """Forwards the payload to the Cloudflare Worker and returns the full JSON response."""
25
- try:
26
- async with aiohttp.ClientSession() as session:
27
- async with session.post(WORKER_URL, json=payload, timeout=60) as response:
28
- if response.status == 200:
29
- data = await response.json()
30
- return data
31
- else:
32
- text = await response.text()
33
- logger.error(f"Worker returned status {response.status}: {text}")
34
- except Exception as e:
35
- logger.error(f"Error forwarding to worker: {e}")
36
- return None
37
-
38
- BOT_STATE = True # Default is ON
39
- NMS_STATE = False # Default is OFF
40
-
41
- @client.on(events.NewMessage)
42
- async def handle_new_message(event):
43
- """
44
- Handles routing of messages:
45
- - /bot on and /bot off commands to control AI state.
46
- - /nms on and /nms off to reply to every message.
47
- - Forwards outgoing commands to worker.
48
- - Forwards incoming PMs/mentions to worker if AI is ON.
49
- """
50
- global BOT_STATE, NMS_STATE
51
- text = event.message.message
52
-
53
- if not text:
54
- return
55
-
56
- is_outgoing = event.out
57
-
58
- # 1. Handle owner commands directly in app.py
59
- if is_outgoing:
60
- lower_text = text.strip().lower()
61
- if lower_text == '/bot on':
62
- BOT_STATE = True
63
- await event.reply("✅ **Userbot AI Mode: ON**\nAI will automatically reply to PMs and mentions.")
64
- return
65
- elif lower_text == '/bot off':
66
- BOT_STATE = False
67
- await event.reply("🛑 **Userbot AI Mode: OFF**\nAI is paused. You can reply manually. (Commands still work)")
68
- return
69
- elif lower_text == '/nms on':
70
- NMS_STATE = True
71
- await event.reply("✅ **NMS Auto-Reply Mode: ON**\nAI will now reply to EVERY incoming message.")
72
- return
73
- elif lower_text == '/nms off':
74
- NMS_STATE = False
75
- await event.reply("🛑 **NMS Auto-Reply Mode: OFF**\nAI stopped replying to every message.")
76
- return
77
- elif lower_text.startswith('/broadcast'):
78
- broadcast_msg = text[10:].strip()
79
- if not broadcast_msg:
80
- await event.reply("❌ စာသားထည့်ပေးပါ။ (ဥပမာ- `/broadcast မင်္ဂလာပါ`)")
81
- return
82
-
83
- await event.reply("🚀 သင်ရောက်ရှိနေသော Group အားလုံးဆီသို့ Broadcast စတင်ပို့ဆောင်နေပါပြီ...")
84
- success_count = 0
85
- fail_count = 0
86
-
87
- async for dialog in client.iter_dialogs():
88
- if dialog.is_group:
89
- try:
90
- await client.send_message(dialog.id, broadcast_msg, parse_mode='html')
91
- success_count += 1
92
- await asyncio.sleep(0.5)
93
- except Exception as e:
94
- logger.error(f"Failed to broadcast to {dialog.name} ({dialog.id}): {e}")
95
- fail_count += 1
96
-
97
- await event.reply(f"✅ **Broadcast ပြီးဆုံးပါပြီ။**\n- အောင်မြင်: {success_count} Groups\n- ကျရှုံး: {fail_count} Groups")
98
- return
99
-
100
- # 2. Determine if we should forward the message to the Worker
101
- should_forward = False
102
- is_command = text.startswith(('/', '.', '!'))
103
-
104
- if is_outgoing:
105
- # Always forward owner's commands (except the ones handled above) to worker
106
-
107
- if is_command:
108
- should_forward = True
109
- else:
110
- # For incoming messages, check NMS_STATE first, then BOT_STATE
111
- if NMS_STATE:
112
- should_forward = True
113
- elif BOT_STATE:
114
- if event.is_private or event.mentioned:
115
- should_forward = True
116
-
117
- if not should_forward:
118
- return
119
-
120
- sender = await event.get_sender()
121
-
122
- # Prepare payload exactly as the Cloudflare Worker expects it for userbot_request
123
- payload = {
124
- "userbot_request": True,
125
- "text": text,
126
- "chat_id": event.chat_id,
127
- "user_id": event.sender_id,
128
- "user_name": getattr(sender, 'first_name', 'User') if sender else 'User',
129
- "is_group": event.is_group
130
- }
131
-
132
- # Handle replies
133
- if event.is_reply:
134
- reply_msg = await event.get_reply_message()
135
- if reply_msg:
136
- payload["reply_to_message_id"] = reply_msg.id
137
- if reply_msg.sender_id:
138
- payload["reply_user_id"] = reply_msg.sender_id
139
-
140
- # Add command compatibility: if owner uses a dot prefix, treat it as slash for the worker
141
- if is_outgoing and text.startswith('.'):
142
- payload["text"] = '/' + text[1:]
143
-
144
- logger.info(f"Forwarding payload to worker: {payload}")
145
- worker_data = await forward_to_worker(payload)
146
-
147
- if worker_data and worker_data.get("ok"):
148
- # Handle Standard Text Response
149
- response_text = worker_data.get("response")
150
- if response_text:
151
- try:
152
- await event.reply(response_text, parse_mode='html')
153
- except Exception as e:
154
- logger.error(f"Error sending response to Telegram: {e}")
155
-
156
- # --- Dummy Web Server (Keep-Alive for Hugging Face Spaces) ---
157
- async def handle_ping(request):
158
- return web.Response(text="Userbot is running!")
159
-
160
- async def start_web_server():
161
- app = web.Application()
162
- app.router.add_get('/', handle_ping)
163
- runner = web.AppRunner(app)
164
- await runner.setup()
165
- port = int(os.environ.get('PORT', 7860))
166
- site = web.TCPSite(runner, '0.0.0.0', port)
167
- await site.start()
168
- logger.info(f"Web server started on port {port}")
169
-
170
- async def main():
171
- await client.start()
172
- logger.info("Userbot started successfully!")
173
-
174
- # Start the dummy web server
175
- await start_web_server()
176
-
177
- # Run the bot until disconnected
178
- await client.run_until_disconnected()
179
-
180
- if __name__ == '__main__':
181
- # Run the asyncio event loop
182
- asyncio.run(main())