Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,944 +1,850 @@
|
|
1 |
-
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
import
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
from
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
from
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
if
|
25 |
-
print("
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
if
|
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 |
-
return await
|
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 |
-
context.user_data['
|
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 |
-
await
|
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 |
-
return
|
451 |
-
|
452 |
-
async def
|
453 |
-
file_id =
|
454 |
-
|
455 |
-
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
|
456 |
-
|
457 |
-
download_path = os.path.join(DOWNLOAD_DIR, f"
|
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 |
-
if
|
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 |
-
if
|
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 |
-
await processing_message.edit_text(get_message(context, '
|
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 |
-
async def
|
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 |
-
CUT_AUDIO_FILE: [
|
852 |
-
MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_cut_audio_file),
|
853 |
-
MessageHandler(filters.VOICE & ~filters.COMMAND, handle_cut_audio_file),
|
854 |
-
CommandHandler("start", start),
|
855 |
-
CommandHandler("cancel", cancel)
|
856 |
-
],
|
857 |
-
CUT_AUDIO_RANGE: [
|
858 |
-
MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range),
|
859 |
-
CommandHandler("start", start),
|
860 |
-
CommandHandler("cancel", cancel)
|
861 |
-
],
|
862 |
-
VIDEO_CONVERSION_MODE: [
|
863 |
-
MessageHandler(filters.VIDEO & ~filters.COMMAND, handle_video_conversion),
|
864 |
-
MessageHandler(filters.VIDEO_NOTE & ~filters.COMMAND, handle_video_conversion),
|
865 |
-
CommandHandler("start", start),
|
866 |
-
CommandHandler("cancel", cancel)
|
867 |
-
],
|
868 |
-
WAITING_FOR_MEMBERSHIP: [
|
869 |
-
CallbackQueryHandler(check_membership_callback, pattern='^check_membership$'),
|
870 |
-
CommandHandler("start", start),
|
871 |
-
CommandHandler("cancel", cancel)
|
872 |
-
],
|
873 |
-
ADMIN_MENU: [
|
874 |
-
CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
|
875 |
-
CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
|
876 |
-
CommandHandler("start", start),
|
877 |
-
CommandHandler("cancel", cancel)
|
878 |
-
],
|
879 |
-
ADD_CHANNEL: [
|
880 |
-
MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel),
|
881 |
-
CommandHandler("start", start),
|
882 |
-
CommandHandler("cancel", cancel)
|
883 |
-
],
|
884 |
-
LIST_REMOVE_CHANNELS: [
|
885 |
-
CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_'),
|
886 |
-
CommandHandler("start", start),
|
887 |
-
CommandHandler("cancel", cancel)
|
888 |
-
]
|
889 |
-
},
|
890 |
-
fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
|
891 |
-
allow_reentry=True
|
892 |
-
)
|
893 |
-
|
894 |
-
application.add_handler(conv_handler)
|
895 |
-
application.add_error_handler(error_handler)
|
896 |
-
print("Telegram bot Application initialized.")
|
897 |
-
|
898 |
-
@app.route("/")
|
899 |
-
async def index():
|
900 |
-
"""Health check endpoint."""
|
901 |
-
return jsonify({"status": "ok", "message": "Telegram bot is running."})
|
902 |
-
|
903 |
-
@app.route("/webhook", methods=["POST"])
|
904 |
-
async def webhook():
|
905 |
-
"""Endpoint for Telegram updates."""
|
906 |
-
await setup_bot() # Ensure bot is initialized
|
907 |
-
update = Update.de_json(request.get_json(force=True), application.bot)
|
908 |
-
await application.process_update(update)
|
909 |
-
return "ok"
|
910 |
-
|
911 |
-
@app.route("/set_webhook", methods=["GET"])
|
912 |
-
async def set_webhook_route():
|
913 |
-
"""
|
914 |
-
Endpoint to manually set the Telegram webhook.
|
915 |
-
Call this once after deploying your Hugging Face Space.
|
916 |
-
Replace <YOUR_HF_SPACE_URL> with your actual Space URL.
|
917 |
-
Example: https://<YOUR_HF_USERNAME>/<YOUR_SPACE_NAME>.hf.space/webhook
|
918 |
-
"""
|
919 |
-
await setup_bot() # Ensure bot is initialized
|
920 |
-
# Replace with your actual Hugging Face Space URL
|
921 |
-
# Example: https://your-username-your-space-name.hf.space/webhook
|
922 |
-
webhook_url = os.getenv("WEBHOOK_URL")
|
923 |
-
if not webhook_url:
|
924 |
-
return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
|
925 |
-
|
926 |
-
# Ensure the webhook URL ends with /webhook
|
927 |
-
if not webhook_url.endswith("/webhook"):
|
928 |
-
webhook_url = f"{webhook_url.rstrip('/')}/webhook"
|
929 |
-
|
930 |
-
try:
|
931 |
-
# Set the webhook with Telegram
|
932 |
-
await application.bot.set_webhook(url=webhook_url)
|
933 |
-
return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
|
934 |
-
except Exception as e:
|
935 |
-
return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
|
936 |
-
|
937 |
-
if __name__ == "__main__":
|
938 |
-
# This block is for local testing or if Hugging Face uses `python app.py` directly
|
939 |
-
# In Hugging Face, gunicorn usually handles running the Flask app.
|
940 |
-
# For local testing, you can run this file directly.
|
941 |
-
# For Hugging Face, the `app` object is what's served by gunicorn.
|
942 |
-
print("Starting Flask app...")
|
943 |
-
app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860))) # Hugging Face uses PORT 7860 by default
|
944 |
�
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import re
|
4 |
+
import subprocess
|
5 |
+
import json
|
6 |
+
from io import BytesIO
|
7 |
+
|
8 |
+
from flask import Flask, request, jsonify
|
9 |
+
|
10 |
+
from telegram import Update, InputFile, InlineKeyboardButton, InlineKeyboardMarkup
|
11 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ConversationHandler
|
12 |
+
from telegram.constants import ParseMode
|
13 |
+
|
14 |
+
from pydub import AudioSegment
|
15 |
+
|
16 |
+
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
17 |
+
if not TOKEN:
|
18 |
+
print("Error: TELEGRAM_BOT_TOKEN environment variable not set.", file=sys.stderr)
|
19 |
+
sys.exit(1)
|
20 |
+
|
21 |
+
BOT_USERNAME = os.getenv("TELEGRAM_BOT_USERNAME", "Voice2mp3_RoBot")
|
22 |
+
|
23 |
+
ADMIN_ID = int(os.getenv("TELEGRAM_ADMIN_ID", "0"))
|
24 |
+
if ADMIN_ID == 0:
|
25 |
+
print("Warning: TELEGRAM_ADMIN_ID environment variable not set or set to 0. Admin features might not work.", file=sys.stderr)
|
26 |
+
|
27 |
+
DOWNLOAD_DIR = "/tmp/downloads"
|
28 |
+
OUTPUT_DIR = "/tmp/outputs"
|
29 |
+
CHANNELS_FILE = "channels.json"
|
30 |
+
|
31 |
+
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
|
32 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
33 |
+
|
34 |
+
def load_required_channels():
|
35 |
+
if os.path.exists(CHANNELS_FILE):
|
36 |
+
try:
|
37 |
+
with open(CHANNELS_FILE, 'r', encoding='utf-8') as f:
|
38 |
+
return json.load(f)
|
39 |
+
except json.JSONDecodeError:
|
40 |
+
print(f"Error decoding JSON from {CHANNELS_FILE}. Starting with empty list.", file=sys.stderr)
|
41 |
+
return []
|
42 |
+
return []
|
43 |
+
|
44 |
+
def save_required_channels(channels):
|
45 |
+
with open(CHANNELS_FILE, 'w', encoding='utf-8') as f:
|
46 |
+
json.dump(channels, f, indent=4, ensure_ascii=False)
|
47 |
+
|
48 |
+
REQUIRED_CHANNELS = load_required_channels()
|
49 |
+
|
50 |
+
LANGUAGE_SELECTION, MAIN_MENU, CONVERT_AUDIO, CUT_AUDIO_FILE, CUT_AUDIO_RANGE, \
|
51 |
+
VIDEO_CONVERSION_MODE, WAITING_FOR_MEMBERSHIP, \
|
52 |
+
ADMIN_MENU, ADD_CHANNEL, LIST_REMOVE_CHANNELS = range(10)
|
53 |
+
|
54 |
+
MESSAGES = {
|
55 |
+
'fa': {
|
56 |
+
'start_welcome': "سلام! من یک ربات تبدیل فرمت صوتی و ویدیویی هستم.\n\nبرای شروع، از منوی زیر یک قابلیت را انتخاب کنید.",
|
57 |
+
'choose_language': "زبان مورد نظر خود را انتخاب کنید:",
|
58 |
+
'processing_start': "⏳ در حال شروع پردازش...",
|
59 |
+
'file_received': "⬇️ فایل دریافت شد. در حال تبدیل...",
|
60 |
+
'conversion_done': "⚙️ تبدیل فرمت انجام شد. در حال ارسال...",
|
61 |
+
'mp3_to_voice_reply': "ویس تلگرام شما (تبدیل شده از MP3)",
|
62 |
+
'voice_to_mp3_caption': "فایل MP3 شما (تبدیل شده از ویس تلگرام)",
|
63 |
+
'error_mp3_to_voice': "❌ خطا در تبدیل MP3 به ویس تلگرام: ",
|
64 |
+
'error_voice_to_mp3': "❌ خطا در تبدیل ویس تلگرام به MP3: ",
|
65 |
+
'general_error': "متاسفم، مشکلی پیش آمد. لطفاً دوباره تلاش کنید.",
|
66 |
+
'main_menu_prompt': "چه کاری میخواهید روی فایل خود انجام دهید؟",
|
67 |
+
'btn_convert_format': "تغییر فرمت صدا �",
|
68 |
+
'btn_cut_audio': "برش قسمتی از صدا ✂️",
|
69 |
+
'btn_video_conversion': "تبدیل ویدیو دایرهای 🎥",
|
70 |
+
'convert_mode_active': "شما در حالت 'تغییر فرمت صدا' هستید. حالا فایل صوتی (ویس یا MP3) خود را برای من ارسال کنید.",
|
71 |
+
'cut_mode_active_file': "شما در قسمت 'برش و کات کردن صدا' هستید.\n\nابتدا فایل صوتی (MP3 یا ویس) خود را ارسال کنید.",
|
72 |
+
'cut_mode_active_range': "حالا بازه زمانی مورد نظر برای برش را به صورت 'دقیقه.ثانیه-دقیقه.ثانیه' (مثال: 00.21-00.54) ارسال کنید.",
|
73 |
+
'invalid_time_format': "فرمت زمان وارد شده صحیح نیست. لطفاً از فرمت 'MM.SS-MM.SS' استفاده کنید. (مثال: 00.21-00.54)",
|
74 |
+
'invalid_time_range': "بازه زمانی نامعتبر است یا زمان پایان از زمان شروع کمتر است. لطفاً بازه صحیح را وارد کنید.",
|
75 |
+
'audio_cut_success': "✅ برش صدا با موفقیت انجام شد. فایل شما آماده است.",
|
76 |
+
'no_audio_for_cut': "فایلی برای برش پیدا نشد. لطفاً ابتدا فایل صوتی را ارسال کنید.",
|
77 |
+
'cut_processing': "✂️ در حال برش صدا...",
|
78 |
+
'returning_to_main_menu': "بازگشت به منوی اصلی...",
|
79 |
+
'cancel_message': "عملیات لغو شد. به منوی اصلی بازگشتید.",
|
80 |
+
'video_conversion_mode_active': "شما در حالت 'تبدیل ویدیو دایرهای' هستید.\n\nیک ویدیو معمولی یا یک ویدیو دایرهای (Video Message) برای من ارسال کنید.",
|
81 |
+
'file_received_video': "⬇️ فایل ویدیویی دریافت شد. در حال پردازش...",
|
82 |
+
'converting_video_note_to_video': "🔄 در حال تبدیل ویدیو دایرهای به ویدیو معمولی...",
|
83 |
+
'converting_video_to_video_note': "🔄 در حال تبدیل ویدیو معمولی به ویدیو دایرهای...",
|
84 |
+
'conversion_done_video': "✅ تبدیل ویدیو با موفقیت انجام شد. در حال ارسال...",
|
85 |
+
'video_note_to_video_caption': "ویدیو معمولی شما (تبدیل شده از ویدیو دایرهای)",
|
86 |
+
'video_to_video_note_reply': "ویدیو دایرهای شما (تبدیل شده از ویدیو معمولی)",
|
87 |
+
'error_video_conversion': "❌ خطا در تبدیل ویدیو: ",
|
88 |
+
'invalid_file_type_video': "لطفاً یک فایل ویدیویی یا ویدیو دایرهای ارسال کنید.",
|
89 |
+
'membership_required': "برای ادامه کار با ربات و استفاده نامحدود، لطفاً ابتدا عضو کانالهای زیر شوید:",
|
90 |
+
'btn_join_channel': "عضو شدن 🤝",
|
91 |
+
'btn_check_membership': "بررسی عضویت ✅",
|
92 |
+
'membership_success': "✅ عضویت شما تأیید شد! اکنون میتوانید به صورت نامحدود از ربات استفاده کنید.",
|
93 |
+
'membership_failed': "❌ متاسفم، شما هنوز عضو تمام کانالهای مورد نیاز نیستید. لطفاً ابتدا عضو شوید و سپس دوباره 'بررسی عضویت' را بزنید.",
|
94 |
+
'not_admin': "شما اجازه دسترسی به این بخش را ندارید.",
|
95 |
+
'admin_menu_prompt': "به پنل مدیریت لینکها خوش آمدید:",
|
96 |
+
'btn_add_channel': "افزودن لینک کانال ➕",
|
97 |
+
'btn_list_channels': "لیست کانالها و حذف 🗑️",
|
98 |
+
'send_channel_link': "لطفاً لینک (مانند @mychannel) یا آیدی عددی کانال را ارسال کنید:",
|
99 |
+
'channel_added': "✅ کانال '{channel_id}' با موفقیت اضافه شد.",
|
100 |
+
'channel_already_exists': "❗️ این کانال قبلاً اضافه شده است.",
|
101 |
+
'no_channels_configured': "هیچ کانالی برای عضویت پیکربندی نشده است.",
|
102 |
+
'channel_list_prompt': "لیست کانالهای فعلی برای عضویت اجباری:",
|
103 |
+
'btn_remove_channel': "حذف ❌",
|
104 |
+
'channel_removed': "✅ کانال '{channel_id}' با موفقیت حذف شد.",
|
105 |
+
'channel_not_found': "❗️ کانال مورد نظر یافت نشد.",
|
106 |
+
'invalid_channel_id': "آیدی/لینک کانال نامعتبر است. لطفاً @username یا آیدی عددی (مانند -1001234567890) را ارسال کنید.",
|
107 |
+
'bot_not_admin_in_channel': "ربات ادمین کانال '{channel_id}' نیست یا مجوزهای کافی برای بررسی عضویت را ندارد. لطفاً ربات را به عنوان ادمین با مجوز 'بررسی وضعیت اعضا' در کانال اضافه کنید."
|
108 |
+
},
|
109 |
+
'en': {
|
110 |
+
'start_welcome': "Hello! I am an audio and video format conversion bot.\n\nTo start, select a feature from the menu below.",
|
111 |
+
'choose_language': "Choose your preferred language:",
|
112 |
+
'processing_start': "⏳ Starting processing...",
|
113 |
+
'file_received': "⬇️ File received. Processing...",
|
114 |
+
'conversion_done': "⚙️ Conversion complete. Sending...",
|
115 |
+
'mp3_to_voice_reply': "Your Telegram voice (converted from MP3)",
|
116 |
+
'voice_to_mp3_caption': "Your MP3 file (converted from Telegram voice)",
|
117 |
+
'error_mp3_to_voice': "❌ Error converting MP3 to Telegram voice: ",
|
118 |
+
'error_voice_to_mp3': "❌ Error converting Telegram voice to MP3: ",
|
119 |
+
'general_error': "Sorry, something went wrong. Please try again.",
|
120 |
+
'main_menu_prompt': "What would you like to do with your file?",
|
121 |
+
'btn_convert_format': "Change Audio Format 🎵",
|
122 |
+
'btn_cut_audio': "Cut Part of Audio ✂️",
|
123 |
+
'btn_video_conversion': "Convert Circular Video 🎥",
|
124 |
+
'convert_mode_active': "You are now in 'Change Audio Format' mode. Send me your audio file (voice or MP3).",
|
125 |
+
'cut_mode_active_file': "You are in the 'Cut Audio' section.\n\nFirst, send your audio file (MP3 or voice).",
|
126 |
+
'cut_mode_active_range': "Now send the desired time range for cutting in 'MM.SS-MM.SS' format (example: 00.21-00.54).",
|
127 |
+
'invalid_time_format': "Invalid time format. Please use 'MM.SS-MM.SS' format. (example: 00.21-00.54)",
|
128 |
+
'invalid_time_range': "Invalid time range or end time is less than start time. Please enter a valid range.",
|
129 |
+
'audio_cut_success': "✅ Audio cut successfully. Your file is ready.",
|
130 |
+
'no_audio_for_cut': "No audio file found for cutting. Please send the audio file first.",
|
131 |
+
'cut_processing': "✂️ Cutting audio...",
|
132 |
+
'returning_to_main_menu': "Returning to main menu...",
|
133 |
+
'cancel_message': "Operation cancelled. Returned to main menu.",
|
134 |
+
'video_conversion_mode_active': "You are in 'Circular Video Conversion' mode.\n\nSend me a regular video or a circular video message (Video Message).",
|
135 |
+
'file_received_video': "⬇️ Video file received. Processing...",
|
136 |
+
'converting_video_note_to_video': "🔄 Converting circular video to regular video...",
|
137 |
+
'converting_video_to_video_note': "🔄 Converting regular video to circular video...",
|
138 |
+
'conversion_done_video': "✅ Video conversion successful. Sending...",
|
139 |
+
'video_note_to_video_caption': "Your regular video (converted from circular video)",
|
140 |
+
'video_to_video_note_reply': "Your circular video (converted from regular video)",
|
141 |
+
'error_video_conversion': "❌ Error converting video: ",
|
142 |
+
'invalid_file_type_video': "Please send a video file or a video message.",
|
143 |
+
'membership_required': "To continue using the bot and access unlimited features, please join the following channels first:",
|
144 |
+
'btn_join_channel': "Join Channel 🤝",
|
145 |
+
'btn_check_membership': "Check Membership ✅",
|
146 |
+
'membership_success': "✅ Your membership has been verified! You can now use the bot unlimitedly.",
|
147 |
+
'membership_failed': "❌ Sorry, you are not yet a member of all required channels. Please join first and then press 'Check Membership' again.",
|
148 |
+
'not_admin': "You do not have permission to access this section.",
|
149 |
+
'admin_menu_prompt': "Welcome to the link management panel:",
|
150 |
+
'btn_add_channel': "Add Channel Link ➕",
|
151 |
+
'btn_list_channels': "List Channels & Remove 🗑️",
|
152 |
+
'send_channel_link': "Please send the channel link (e.g., @mychannel) or numeric ID:",
|
153 |
+
'channel_added': "✅ Channel '{channel_id}' successfully added.",
|
154 |
+
'channel_already_exists': "❗️ This channel has already been added.",
|
155 |
+
'no_channels_configured': "No channels configured for membership.",
|
156 |
+
'channel_list_prompt': "Current list of channels for mandatory membership:",
|
157 |
+
'btn_remove_channel': "Remove ❌",
|
158 |
+
'channel_removed': "✅ Channel '{channel_id}' successfully removed.",
|
159 |
+
'channel_not_found': "❗️ Channel not found.",
|
160 |
+
'invalid_channel_id': "Invalid channel ID/link. Please send @username or numeric ID (e.g., -1001234567890).",
|
161 |
+
'bot_not_admin_in_channel': "The bot is not an admin in channel '{channel_id}' or does not have sufficient permissions to check membership. Please add the bot as an admin with 'Check members' permission in the channel."
|
162 |
+
}
|
163 |
+
}
|
164 |
+
|
165 |
+
def get_message(context, key, **kwargs):
|
166 |
+
lang = context.user_data.get('language', 'fa')
|
167 |
+
message_template = MESSAGES[lang].get(key, MESSAGES['fa'][key])
|
168 |
+
return message_template.format(**kwargs)
|
169 |
+
|
170 |
+
def parse_time_to_ms(time_str):
|
171 |
+
match = re.match(r'^(\d{2})\.(\d{2})$', time_str)
|
172 |
+
if not match:
|
173 |
+
raise ValueError("Invalid time format")
|
174 |
+
|
175 |
+
minutes = int(match.group(1))
|
176 |
+
seconds = int(match.group(2))
|
177 |
+
|
178 |
+
if seconds >= 60:
|
179 |
+
raise ValueError("Seconds must be between 00 and 59")
|
180 |
+
|
181 |
+
return (minutes * 60 + seconds) * 1000
|
182 |
+
|
183 |
+
async def check_user_membership(update: Update, context):
|
184 |
+
user_id = update.effective_user.id
|
185 |
+
|
186 |
+
if not REQUIRED_CHANNELS:
|
187 |
+
return True
|
188 |
+
|
189 |
+
all_channels_joined = True
|
190 |
+
for channel_id in REQUIRED_CHANNELS:
|
191 |
+
try:
|
192 |
+
chat_member = await context.bot.get_chat_member(chat_id=channel_id, user_id=user_id)
|
193 |
+
if chat_member.status not in ['member', 'administrator', 'creator']:
|
194 |
+
all_channels_joined = False
|
195 |
+
break
|
196 |
+
except Exception as e:
|
197 |
+
print(f"Error checking membership for channel {channel_id}: {e}", file=sys.stderr)
|
198 |
+
all_channels_joined = False
|
199 |
+
break
|
200 |
+
return all_channels_joined
|
201 |
+
|
202 |
+
async def show_membership_required_message(update: Update, context):
|
203 |
+
keyboard = []
|
204 |
+
if not REQUIRED_CHANNELS:
|
205 |
+
return await show_main_menu(update, context)
|
206 |
+
|
207 |
+
for channel_id in REQUIRED_CHANNELS:
|
208 |
+
try:
|
209 |
+
chat = await context.bot.get_chat(chat_id=channel_id)
|
210 |
+
if chat.invite_link:
|
211 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {chat.title or channel_id}", url=chat.invite_link)])
|
212 |
+
elif chat.username:
|
213 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} @{chat.username}", url=f"https://t.me/{chat.username}")])
|
214 |
+
else:
|
215 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
|
216 |
+
except Exception as e:
|
217 |
+
print(f"Could not get chat info for {channel_id}: {e}", file=sys.stderr)
|
218 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_join_channel')} {channel_id}", callback_data=f"no_link_{channel_id}")])
|
219 |
+
|
220 |
+
keyboard.append([InlineKeyboardButton(get_message(context, 'btn_check_membership'), callback_data='check_membership')])
|
221 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
222 |
+
|
223 |
+
if update.callback_query:
|
224 |
+
await update.callback_query.edit_message_text(
|
225 |
+
get_message(context, 'membership_required'),
|
226 |
+
reply_markup=reply_markup
|
227 |
+
)
|
228 |
+
else:
|
229 |
+
await update.effective_message.reply_text(
|
230 |
+
get_message(context, 'membership_required'),
|
231 |
+
reply_markup=reply_markup
|
232 |
+
)
|
233 |
+
return WAITING_FOR_MEMBERSHIP
|
234 |
+
|
235 |
+
async def process_feature_or_check_membership(update: Update, context, feature_func, *args, **kwargs):
|
236 |
+
user_id = update.effective_user.id
|
237 |
+
|
238 |
+
if user_id == ADMIN_ID:
|
239 |
+
return await feature_func(update, context, *args, **kwargs)
|
240 |
+
|
241 |
+
if not REQUIRED_CHANNELS:
|
242 |
+
return await feature_func(update, context, *args, **kwargs)
|
243 |
+
|
244 |
+
if context.user_data.get('used_bot_once', False) and not context.user_data.get('is_member', False):
|
245 |
+
return await show_membership_required_message(update, context)
|
246 |
+
|
247 |
+
if not context.user_data.get('used_bot_once', False):
|
248 |
+
context.user_data['used_bot_once'] = True
|
249 |
+
is_member = await check_user_membership(update, context)
|
250 |
+
context.user_data['is_member'] = is_member
|
251 |
+
if not is_member:
|
252 |
+
return await show_membership_required_message(update, context)
|
253 |
+
|
254 |
+
result = await feature_func(update, context, *args, **kwargs)
|
255 |
+
|
256 |
+
if not context.user_data.get('is_member', False):
|
257 |
+
return await show_membership_required_message(update, context)
|
258 |
+
|
259 |
+
return result
|
260 |
+
|
261 |
+
async def check_membership_callback(update: Update, context):
|
262 |
+
query = update.callback_query
|
263 |
+
await query.answer()
|
264 |
+
|
265 |
+
is_member = await check_user_membership(update, context)
|
266 |
+
if is_member:
|
267 |
+
context.user_data['is_member'] = True
|
268 |
+
await query.edit_message_text(get_message(context, 'membership_success'))
|
269 |
+
return await show_main_menu(update, context)
|
270 |
+
else:
|
271 |
+
await query.edit_message_text(get_message(context, 'membership_failed'),
|
272 |
+
reply_markup=query.message.reply_markup)
|
273 |
+
return WAITING_FOR_MEMBERSHIP
|
274 |
+
|
275 |
+
async def start(update: Update, context):
|
276 |
+
keyboard = [
|
277 |
+
[InlineKeyboardButton("فارسی 🇮🇷", callback_data='set_lang_fa')],
|
278 |
+
[InlineKeyboardButton("English 🇬🇧", callback_data='set_lang_en')]
|
279 |
+
]
|
280 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
281 |
+
|
282 |
+
await update.message.reply_text(
|
283 |
+
"زبان مورد نظر خود را انتخاب کنید:\nChoose your preferred language:",
|
284 |
+
reply_markup=reply_markup
|
285 |
+
)
|
286 |
+
return LANGUAGE_SELECTION
|
287 |
+
|
288 |
+
async def set_language(update: Update, context):
|
289 |
+
query = update.callback_query
|
290 |
+
await query.answer()
|
291 |
+
|
292 |
+
lang_code = query.data.replace('set_lang_', '')
|
293 |
+
context.user_data['language'] = lang_code
|
294 |
+
|
295 |
+
welcome_message = get_message(context, 'start_welcome')
|
296 |
+
await query.edit_message_text(text=welcome_message)
|
297 |
+
|
298 |
+
return await process_feature_or_check_membership(update, context, show_main_menu)
|
299 |
+
|
300 |
+
async def show_main_menu(update: Update, context):
|
301 |
+
keyboard = [
|
302 |
+
[InlineKeyboardButton(get_message(context, 'btn_convert_format'), callback_data='select_convert_format')],
|
303 |
+
[InlineKeyboardButton(get_message(context, 'btn_cut_audio'), callback_data='select_cut_audio')],
|
304 |
+
[InlineKeyboardButton(get_message(context, 'btn_video_conversion'), callback_data='select_video_conversion')]
|
305 |
+
]
|
306 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
307 |
+
|
308 |
+
if update.callback_query:
|
309 |
+
await update.callback_query.edit_message_text(
|
310 |
+
text=get_message(context, 'main_menu_prompt'),
|
311 |
+
reply_markup=reply_markup
|
312 |
+
)
|
313 |
+
else:
|
314 |
+
await update.message.reply_text(
|
315 |
+
text=get_message(context, 'main_menu_prompt'),
|
316 |
+
reply_markup=reply_markup
|
317 |
+
)
|
318 |
+
return MAIN_MENU
|
319 |
+
|
320 |
+
async def change_format_selected(update: Update, context):
|
321 |
+
query = update.callback_query
|
322 |
+
await query.answer()
|
323 |
+
await query.edit_message_text(text=get_message(context, 'convert_mode_active'))
|
324 |
+
return CONVERT_AUDIO
|
325 |
+
|
326 |
+
async def cut_audio_selected(update: Update, context):
|
327 |
+
query = update.callback_query
|
328 |
+
await query.answer()
|
329 |
+
await query.edit_message_text(text=get_message(context, 'cut_mode_active_file'))
|
330 |
+
context.user_data['audio_for_cut_path'] = None
|
331 |
+
return CUT_AUDIO_FILE
|
332 |
+
|
333 |
+
async def video_conversion_selected(update: Update, context):
|
334 |
+
query = update.callback_query
|
335 |
+
await query.answer()
|
336 |
+
await query.edit_message_text(text=get_message(context, 'video_conversion_mode_active'))
|
337 |
+
return VIDEO_CONVERSION_MODE
|
338 |
+
|
339 |
+
async def handle_audio(update: Update, context):
|
340 |
+
if not update.message.audio:
|
341 |
+
return CONVERT_AUDIO
|
342 |
+
|
343 |
+
async def _perform_conversion(update: Update, context):
|
344 |
+
file_id = update.message.audio.file_id
|
345 |
+
file_name = update.message.audio.file_name if update.message.audio.file_name else f"audio_{file_id}.mp3"
|
346 |
+
|
347 |
+
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
|
348 |
+
|
349 |
+
download_path = os.path.join(DOWNLOAD_DIR, file_name)
|
350 |
+
output_ogg_path = os.path.join(OUTPUT_DIR, f"{os.path.splitext(file_name)[0]}.ogg")
|
351 |
+
|
352 |
+
try:
|
353 |
+
new_file = await context.bot.get_file(file_id)
|
354 |
+
await new_file.download_to_drive(download_path)
|
355 |
+
|
356 |
+
await processing_message.edit_text(get_message(context, 'file_received'))
|
357 |
+
|
358 |
+
audio = AudioSegment.from_mp3(download_path)
|
359 |
+
audio.export(output_ogg_path, format="ogg", codec="libopus", parameters=["-b:a", "32k"])
|
360 |
+
|
361 |
+
await processing_message.edit_text(get_message(context, 'conversion_done'))
|
362 |
+
|
363 |
+
with open(output_ogg_path, 'rb') as f_read:
|
364 |
+
ogg_file_bytes_io = BytesIO(f_read.read())
|
365 |
+
|
366 |
+
sent_voice_message = await update.message.reply_voice(InputFile(ogg_file_bytes_io, filename=os.path.basename(output_ogg_path)))
|
367 |
+
ogg_file_bytes_io.close()
|
368 |
+
|
369 |
+
if sent_voice_message:
|
370 |
+
await sent_voice_message.reply_text(get_message(context, 'mp3_to_voice_reply'))
|
371 |
+
|
372 |
+
await processing_message.delete()
|
373 |
+
return CONVERT_AUDIO
|
374 |
+
|
375 |
+
except Exception as e:
|
376 |
+
print(f"Error converting MP3 to voice: {e}", file=sys.stderr)
|
377 |
+
if processing_message:
|
378 |
+
await processing_message.edit_text(get_message(context, 'error_mp3_to_voice') + str(e))
|
379 |
+
else:
|
380 |
+
await update.message.reply_text(get_message(context, 'error_mp3_to_voice') + str(e))
|
381 |
+
return CONVERT_AUDIO
|
382 |
+
finally:
|
383 |
+
if os.path.exists(download_path):
|
384 |
+
os.remove(download_path)
|
385 |
+
if os.path.exists(output_ogg_path):
|
386 |
+
os.remove(output_ogg_path)
|
387 |
+
|
388 |
+
return await process_feature_or_check_membership(update, context, _perform_conversion)
|
389 |
+
|
390 |
+
|
391 |
+
async def handle_voice(update: Update, context):
|
392 |
+
if not update.message.voice:
|
393 |
+
return CONVERT_AUDIO
|
394 |
+
|
395 |
+
async def _perform_conversion(update: Update, context):
|
396 |
+
file_id = update.message.voice.file_id
|
397 |
+
|
398 |
+
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
|
399 |
+
|
400 |
+
download_path = os.path.join(DOWNLOAD_DIR, f"voice_{file_id}.ogg")
|
401 |
+
output_mp3_path = os.path.join(OUTPUT_DIR, f"@{BOT_USERNAME}_{file_id}.mp3")
|
402 |
+
|
403 |
+
try:
|
404 |
+
new_file = await context.bot.get_file(file_id)
|
405 |
+
await new_file.download_to_drive(download_path)
|
406 |
+
|
407 |
+
await processing_message.edit_text(get_message(context, 'file_received'))
|
408 |
+
|
409 |
+
audio = AudioSegment.from_file(download_path, format="ogg")
|
410 |
+
|
411 |
+
export_tags = {
|
412 |
+
'album': BOT_USERNAME,
|
413 |
+
'artist': BOT_USERNAME
|
414 |
+
}
|
415 |
+
audio.export(output_mp3_path, format="mp3", tags=export_tags)
|
416 |
+
|
417 |
+
await processing_message.edit_text(get_message(context, 'conversion_done'))
|
418 |
+
|
419 |
+
with open(output_mp3_path, 'rb') as f_read:
|
420 |
+
mp3_file_bytes_io = BytesIO(f_read.read())
|
421 |
+
|
422 |
+
await update.message.reply_audio(
|
423 |
+
InputFile(mp3_file_bytes_io, filename=os.path.basename(output_mp3_path)),
|
424 |
+
caption=get_message(context, 'voice_to_mp3_caption')
|
425 |
+
)
|
426 |
+
mp3_file_bytes_io.close()
|
427 |
+
|
428 |
+
await processing_message.delete()
|
429 |
+
return CONVERT_AUDIO
|
430 |
+
|
431 |
+
except Exception as e:
|
432 |
+
print(f"Error converting voice to MP3: {e}", file=sys.stderr)
|
433 |
+
if processing_message:
|
434 |
+
await processing_message.edit_text(get_message(context, 'error_voice_to_mp3') + str(e))
|
435 |
+
else:
|
436 |
+
await update.message.reply_text(get_message(context, 'error_voice_to_mp3') + str(e))
|
437 |
+
return CONVERT_AUDIO
|
438 |
+
finally:
|
439 |
+
if os.path.exists(download_path):
|
440 |
+
os.remove(download_path)
|
441 |
+
if os.path.exists(output_mp3_path):
|
442 |
+
os.remove(output_mp3_path)
|
443 |
+
|
444 |
+
return await process_feature_or_check_membership(update, context, _perform_conversion)
|
445 |
+
|
446 |
+
async def handle_cut_audio_file(update: Update, context):
|
447 |
+
audio_file = update.message.audio or update.message.voice
|
448 |
+
if not audio_file:
|
449 |
+
await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
|
450 |
+
return CUT_AUDIO_FILE
|
451 |
+
|
452 |
+
async def _perform_file_receive(update: Update, context):
|
453 |
+
file_id = audio_file.file_id
|
454 |
+
|
455 |
+
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
|
456 |
+
|
457 |
+
download_path = os.path.join(DOWNLOAD_DIR, f"cut_audio_{file_id}.{'mp3' if update.message.audio else 'ogg'}")
|
458 |
+
|
459 |
+
try:
|
460 |
+
new_file = await context.bot.get_file(file_id)
|
461 |
+
await new_file.download_to_drive(download_path)
|
462 |
+
|
463 |
+
context.user_data['audio_for_cut_path'] = download_path
|
464 |
+
context.user_data['audio_for_cut_type'] = 'mp3' if update.message.audio else 'ogg'
|
465 |
+
|
466 |
+
await processing_message.edit_text(get_message(context, 'cut_mode_active_range'))
|
467 |
+
await processing_message.delete()
|
468 |
+
return CUT_AUDIO_RANGE
|
469 |
+
|
470 |
+
except Exception as e:
|
471 |
+
print(f"Error handling cut audio file: {e}", file=sys.stderr)
|
472 |
+
if processing_message:
|
473 |
+
await processing_message.edit_text(get_message(context, 'general_error') + str(e))
|
474 |
+
else:
|
475 |
+
await update.message.reply_text(get_message(context, 'general_error') + str(e))
|
476 |
+
return CUT_AUDIO_FILE
|
477 |
+
|
478 |
+
return await process_feature_or_check_membership(update, context, _perform_file_receive)
|
479 |
+
|
480 |
+
async def handle_cut_audio_range(update: Update, context):
|
481 |
+
time_range_str = update.message.text
|
482 |
+
audio_path = context.user_data.get('audio_for_cut_path')
|
483 |
+
audio_type = context.user_data.get('audio_for_cut_type')
|
484 |
+
|
485 |
+
if not audio_path or not os.path.exists(audio_path):
|
486 |
+
await update.message.reply_text(get_message(context, 'no_audio_for_cut'))
|
487 |
+
return CUT_AUDIO_FILE
|
488 |
+
|
489 |
+
async def _perform_cut(update: Update, context):
|
490 |
+
processing_message = await update.message.reply_text(get_message(context, 'cut_processing'))
|
491 |
+
output_cut_path = None
|
492 |
+
|
493 |
+
try:
|
494 |
+
start_time_str, end_time_str = time_range_str.split('-')
|
495 |
+
start_ms = parse_time_to_ms(start_time_str.strip())
|
496 |
+
end_ms = parse_time_to_ms(end_time_str.strip())
|
497 |
+
|
498 |
+
if start_ms >= end_ms:
|
499 |
+
await processing_message.edit_text(get_message(context, 'invalid_time_range'))
|
500 |
+
return CUT_AUDIO_RANGE
|
501 |
+
|
502 |
+
audio = AudioSegment.from_file(audio_path, format=audio_type)
|
503 |
+
cut_audio = audio[start_ms:end_ms]
|
504 |
+
|
505 |
+
output_cut_path = os.path.join(OUTPUT_DIR, f"cut_{os.path.basename(audio_path).split('.')[0]}.mp3")
|
506 |
+
cut_audio.export(output_cut_path, format="mp3")
|
507 |
+
|
508 |
+
await processing_message.edit_text(get_message(context, 'audio_cut_success'))
|
509 |
+
|
510 |
+
with open(output_cut_path, 'rb') as f_read:
|
511 |
+
cut_file_bytes_io = BytesIO(f_read.read())
|
512 |
+
|
513 |
+
await update.message.reply_audio(InputFile(cut_file_bytes_io, filename=os.path.basename(output_cut_path)),
|
514 |
+
caption=f"برش از {start_time_str} تا {end_time_str}")
|
515 |
+
cut_file_bytes_io.close()
|
516 |
+
|
517 |
+
await processing_message.delete()
|
518 |
+
return await show_main_menu(update, context)
|
519 |
+
|
520 |
+
except ValueError as ve:
|
521 |
+
print(f"Time format or range error: {ve}", file=sys.stderr)
|
522 |
+
await processing_message.edit_text(get_message(context, 'invalid_time_format'))
|
523 |
+
return CUT_AUDIO_RANGE
|
524 |
+
except Exception as e:
|
525 |
+
print(f"Error cutting audio: {e}", file=sys.stderr)
|
526 |
+
if processing_message:
|
527 |
+
await processing_message.edit_text(get_message(context, 'general_error') + str(e))
|
528 |
+
else:
|
529 |
+
await update.message.reply_text(get_message(context, 'general_error') + str(e))
|
530 |
+
return CUT_AUDIO_FILE
|
531 |
+
finally:
|
532 |
+
if os.path.exists(audio_path):
|
533 |
+
os.remove(audio_path)
|
534 |
+
if 'audio_for_cut_path' in context.user_data:
|
535 |
+
del context.user_data['audio_for_cut_path']
|
536 |
+
if 'audio_for_cut_type' in context.user_data:
|
537 |
+
del context.user_data['audio_for_cut_type']
|
538 |
+
if output_cut_path and os.path.exists(output_cut_path):
|
539 |
+
os.remove(output_cut_path)
|
540 |
+
|
541 |
+
return await process_feature_or_check_membership(update, context, _perform_cut)
|
542 |
+
|
543 |
+
async def handle_video_conversion(update: Update, context):
|
544 |
+
file_to_process = None
|
545 |
+
is_video_note = False
|
546 |
+
|
547 |
+
if update.message.video:
|
548 |
+
file_to_process = update.message.video
|
549 |
+
file_name_prefix = "regular_video"
|
550 |
+
input_ext = ".mp4"
|
551 |
+
elif update.message.video_note:
|
552 |
+
file_to_process = update.message.video_note
|
553 |
+
is_video_note = True
|
554 |
+
file_name_prefix = "video_note"
|
555 |
+
input_ext = ".mp4"
|
556 |
+
else:
|
557 |
+
await update.message.reply_text(get_message(context, 'invalid_file_type_video'))
|
558 |
+
return VIDEO_CONVERSION_MODE
|
559 |
+
|
560 |
+
async def _perform_video_conversion(update: Update, context):
|
561 |
+
file_id = file_to_process.file_id
|
562 |
+
download_path = os.path.join(DOWNLOAD_DIR, f"{file_name_prefix}_{file_id}{input_ext}")
|
563 |
+
|
564 |
+
processing_message = await update.message.reply_text(get_message(context, 'processing_start'))
|
565 |
+
|
566 |
+
output_path = None
|
567 |
+
try:
|
568 |
+
new_file = await context.bot.get_file(file_id)
|
569 |
+
await new_file.download_to_drive(download_path)
|
570 |
+
|
571 |
+
await processing_message.edit_text(get_message(context, 'file_received_video'))
|
572 |
+
|
573 |
+
output_file_name = f"{file_name_prefix}_converted_{file_id}.mp4"
|
574 |
+
output_path = os.path.join(OUTPUT_DIR, output_file_name)
|
575 |
+
|
576 |
+
if is_video_note:
|
577 |
+
await processing_message.edit_text(get_message(context, 'converting_video_note_to_video'))
|
578 |
+
ffmpeg_command = [
|
579 |
+
'ffmpeg',
|
580 |
+
'-i', download_path,
|
581 |
+
'-c:v', 'libx264',
|
582 |
+
'-crf', '23',
|
583 |
+
'-preset', 'medium',
|
584 |
+
'-c:a', 'aac',
|
585 |
+
'-b:a', '128k',
|
586 |
+
'-movflags', '+faststart',
|
587 |
+
output_path
|
588 |
+
]
|
589 |
+
subprocess.run(ffmpeg_command, check=True, capture_output=True)
|
590 |
+
|
591 |
+
await processing_message.edit_text(get_message(context, 'conversion_done_video'))
|
592 |
+
|
593 |
+
with open(output_path, 'rb') as f:
|
594 |
+
await update.message.reply_video(InputFile(f, filename=output_file_name),
|
595 |
+
caption=get_message(context, 'video_note_to_video_caption'))
|
596 |
+
else:
|
597 |
+
await processing_message.edit_text(get_message(context, 'converting_video_to_video_note'))
|
598 |
+
ffmpeg_command = [
|
599 |
+
'ffmpeg',
|
600 |
+
'-i', download_path,
|
601 |
+
'-vf', 'crop=min(iw\,ih):min(iw\,ih),scale=640:640',
|
602 |
+
'-c:v', 'libx264',
|
603 |
+
'-crf', '28',
|
604 |
+
'-preset', 'veryfast',
|
605 |
+
'-c:a', 'aac',
|
606 |
+
'-b:a', '64k',
|
607 |
+
'-movflags', '+faststart',
|
608 |
+
output_path
|
609 |
+
]
|
610 |
+
subprocess.run(ffmpeg_command, check=True, capture_output=True)
|
611 |
+
|
612 |
+
await processing_message.edit_text(get_message(context, 'conversion_done_video'))
|
613 |
+
|
614 |
+
with open(output_path, 'rb') as f:
|
615 |
+
await update.message.reply_video_note(InputFile(f, filename=output_file_name))
|
616 |
+
await update.message.reply_text(get_message(context, 'video_to_video_note_reply'))
|
617 |
+
|
618 |
+
await processing_message.delete()
|
619 |
+
return VIDEO_CONVERSION_MODE
|
620 |
+
|
621 |
+
except subprocess.CalledProcessError as e:
|
622 |
+
print(f"FFmpeg error: {e.stdout.decode()} {e.stderr.decode()}", file=sys.stderr)
|
623 |
+
if processing_message:
|
624 |
+
await processing_message.edit_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
|
625 |
+
else:
|
626 |
+
await update.message.reply_text(get_message(context, 'error_video_conversion') + f"FFmpeg Error: {e.stderr.decode()}")
|
627 |
+
return VIDEO_CONVERSION_MODE
|
628 |
+
except Exception as e:
|
629 |
+
print(f"General video conversion error: {e}", file=sys.stderr)
|
630 |
+
if processing_message:
|
631 |
+
await processing_message.edit_text(get_message(context, 'error_video_conversion') + str(e))
|
632 |
+
else:
|
633 |
+
await update.message.reply_text(get_message(context, 'error_video_conversion') + str(e))
|
634 |
+
return VIDEO_CONVERSION_MODE
|
635 |
+
finally:
|
636 |
+
if os.path.exists(download_path):
|
637 |
+
os.remove(download_path)
|
638 |
+
if output_path and os.path.exists(output_path):
|
639 |
+
os.remove(output_path)
|
640 |
+
|
641 |
+
return await process_feature_or_check_membership(update, context, _perform_video_conversion)
|
642 |
+
|
643 |
+
async def cancel(update: Update, context):
|
644 |
+
await update.message.reply_text(get_message(context, 'cancel_message'))
|
645 |
+
if 'audio_for_cut_path' in context.user_data and os.path.exists(context.user_data['audio_for_cut_path']):
|
646 |
+
os.remove(context.user_data['audio_for_cut_path'])
|
647 |
+
del context.user_data['audio_for_cut_path']
|
648 |
+
if 'audio_for_cut_type' in context.user_data:
|
649 |
+
del context.user_data['audio_for_cut_type']
|
650 |
+
|
651 |
+
context.user_data['is_member'] = False
|
652 |
+
context.user_data['used_bot_once'] = False
|
653 |
+
|
654 |
+
return await show_main_menu(update, context)
|
655 |
+
|
656 |
+
async def error_handler(update: Update, context):
|
657 |
+
print(f"Update {update} caused error {context.error}", file=sys.stderr)
|
658 |
+
if update.message:
|
659 |
+
await update.message.reply_text(get_message(context, 'general_error'))
|
660 |
+
return ConversationHandler.END
|
661 |
+
|
662 |
+
async def admin_link_command(update: Update, context):
|
663 |
+
if update.effective_user.id != ADMIN_ID:
|
664 |
+
await update.message.reply_text(get_message(context, 'not_admin'))
|
665 |
+
return ConversationHandler.END
|
666 |
+
|
667 |
+
keyboard = [
|
668 |
+
[InlineKeyboardButton(get_message(context, 'btn_add_channel'), callback_data='admin_add_channel')],
|
669 |
+
[InlineKeyboardButton(get_message(context, 'btn_list_channels'), callback_data='admin_list_channels')]
|
670 |
+
]
|
671 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
672 |
+
await update.message.reply_text(get_message(context, 'admin_menu_prompt'), reply_markup=reply_markup)
|
673 |
+
return ADMIN_MENU
|
674 |
+
|
675 |
+
async def admin_add_channel_prompt(update: Update, context):
|
676 |
+
query = update.callback_query
|
677 |
+
await query.answer()
|
678 |
+
await query.edit_message_text(get_message(context, 'send_channel_link'))
|
679 |
+
return ADD_CHANNEL
|
680 |
+
|
681 |
+
async def admin_handle_add_channel(update: Update, context):
|
682 |
+
channel_input = update.message.text.strip()
|
683 |
+
|
684 |
+
if not (channel_input.startswith('@') or channel_input.startswith('-100')):
|
685 |
+
await update.message.reply_text(get_message(context, 'invalid_channel_id'))
|
686 |
+
return ADD_CHANNEL
|
687 |
+
|
688 |
+
try:
|
689 |
+
chat_member = await context.bot.get_chat_member(chat_id=channel_input, user_id=context.bot.id)
|
690 |
+
if not (chat_member.status == 'administrator' and chat_member.can_invite_users):
|
691 |
+
await update.message.reply_text(get_message(context, 'bot_not_admin_in_channel', channel_id=channel_input))
|
692 |
+
return ADD_CHANNEL
|
693 |
+
except Exception as e:
|
694 |
+
print(f"Error checking bot's admin status in channel {channel_input}: {e}", file=sys.stderr)
|
695 |
+
await update.message.reply_text(get_message(context, 'invalid_channel_id') + f"\nError: {e}")
|
696 |
+
return ADD_CHANNEL
|
697 |
+
|
698 |
+
if channel_input not in REQUIRED_CHANNELS:
|
699 |
+
REQUIRED_CHANNELS.append(channel_input)
|
700 |
+
save_required_channels(REQUIRED_CHANNELS)
|
701 |
+
await update.message.reply_text(get_message(context, 'channel_added', channel_id=channel_input))
|
702 |
+
else:
|
703 |
+
await update.message.reply_text(get_message(context, 'channel_already_exists'))
|
704 |
+
|
705 |
+
return await admin_link_command(update, context)
|
706 |
+
|
707 |
+
async def admin_list_channels(update: Update, context):
|
708 |
+
query = update.callback_query
|
709 |
+
await query.answer()
|
710 |
+
|
711 |
+
if not REQUIRED_CHANNELS:
|
712 |
+
await query.edit_message_text(get_message(context, 'no_channels_configured'))
|
713 |
+
return ADMIN_MENU
|
714 |
+
|
715 |
+
keyboard = []
|
716 |
+
message_text = get_message(context, 'channel_list_prompt') + "\n\n"
|
717 |
+
for i, channel_id in enumerate(REQUIRED_CHANNELS):
|
718 |
+
try:
|
719 |
+
chat = await context.bot.get_chat(chat_id=channel_id)
|
720 |
+
channel_name = chat.title if chat.title else channel_id
|
721 |
+
message_text += f"{i+1}. {channel_name} (`{channel_id}`)\n"
|
722 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_name}", callback_data=f'remove_channel_{channel_id}')])
|
723 |
+
except Exception as e:
|
724 |
+
message_text += f"{i+1}. {channel_id} (خطا در دریافت اطلاعات: {e})\n"
|
725 |
+
keyboard.append([InlineKeyboardButton(f"{get_message(context, 'btn_remove_channel')} {channel_id}", callback_data=f'remove_channel_{channel_id}')])
|
726 |
+
|
727 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
728 |
+
await query.edit_message_text(message_text, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
|
729 |
+
return LIST_REMOVE_CHANNELS
|
730 |
+
|
731 |
+
async def admin_handle_remove_channel(update: Update, context):
|
732 |
+
query = update.callback_query
|
733 |
+
await query.answer()
|
734 |
+
channel_id_to_remove = query.data.replace('remove_channel_', '')
|
735 |
+
|
736 |
+
if channel_id_to_remove in REQUIRED_CHANNELS:
|
737 |
+
REQUIRED_CHANNELS.remove(channel_id_to_remove)
|
738 |
+
save_required_channels(REQUIRED_CHANNELS)
|
739 |
+
await query.edit_message_text(get_message(context, 'channel_removed', channel_id=channel_id_to_remove))
|
740 |
+
else:
|
741 |
+
await query.edit_message_text(get_message(context, 'channel_not_found'))
|
742 |
+
|
743 |
+
return await admin_link_command(update, context)
|
744 |
+
|
745 |
+
app = Flask(__name__)
|
746 |
+
application = None
|
747 |
+
|
748 |
+
async def setup_bot():
|
749 |
+
global application
|
750 |
+
if application is None:
|
751 |
+
application = Application.builder().token(TOKEN).build()
|
752 |
+
|
753 |
+
conv_handler = ConversationHandler(
|
754 |
+
entry_points=[
|
755 |
+
CommandHandler("start", start),
|
756 |
+
CommandHandler("link", admin_link_command)
|
757 |
+
],
|
758 |
+
states={
|
759 |
+
LANGUAGE_SELECTION: [
|
760 |
+
CallbackQueryHandler(set_language, pattern='^set_lang_')
|
761 |
+
],
|
762 |
+
MAIN_MENU: [
|
763 |
+
CallbackQueryHandler(change_format_selected, pattern='^select_convert_format$'),
|
764 |
+
CallbackQueryHandler(cut_audio_selected, pattern='^select_cut_audio$'),
|
765 |
+
CallbackQueryHandler(video_conversion_selected, pattern='^select_video_conversion$')
|
766 |
+
],
|
767 |
+
CONVERT_AUDIO: [
|
768 |
+
MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_audio),
|
769 |
+
MessageHandler(filters.VOICE & ~filters.COMMAND, handle_voice),
|
770 |
+
CommandHandler("start", start),
|
771 |
+
CommandHandler("cancel", cancel)
|
772 |
+
],
|
773 |
+
CUT_AUDIO_FILE: [
|
774 |
+
MessageHandler(filters.AUDIO & ~filters.COMMAND, handle_cut_audio_file),
|
775 |
+
MessageHandler(filters.VOICE & ~filters.COMMAND, handle_cut_audio_file),
|
776 |
+
CommandHandler("start", start),
|
777 |
+
CommandHandler("cancel", cancel)
|
778 |
+
],
|
779 |
+
CUT_AUDIO_RANGE: [
|
780 |
+
MessageHandler(filters.TEXT & ~filters.COMMAND, handle_cut_audio_range),
|
781 |
+
CommandHandler("start", start),
|
782 |
+
CommandHandler("cancel", cancel)
|
783 |
+
],
|
784 |
+
VIDEO_CONVERSION_MODE: [
|
785 |
+
MessageHandler(filters.VIDEO & ~filters.COMMAND, handle_video_conversion),
|
786 |
+
MessageHandler(filters.VIDEO_NOTE & ~filters.COMMAND, handle_video_conversion),
|
787 |
+
CommandHandler("start", start),
|
788 |
+
CommandHandler("cancel", cancel)
|
789 |
+
],
|
790 |
+
WAITING_FOR_MEMBERSHIP: [
|
791 |
+
CallbackQueryHandler(check_membership_callback, pattern='^check_membership$'),
|
792 |
+
CommandHandler("start", start),
|
793 |
+
CommandHandler("cancel", cancel)
|
794 |
+
],
|
795 |
+
ADMIN_MENU: [
|
796 |
+
CallbackQueryHandler(admin_add_channel_prompt, pattern='^admin_add_channel$'),
|
797 |
+
CallbackQueryHandler(admin_list_channels, pattern='^admin_list_channels$'),
|
798 |
+
CommandHandler("start", start),
|
799 |
+
CommandHandler("cancel", cancel)
|
800 |
+
],
|
801 |
+
ADD_CHANNEL: [
|
802 |
+
MessageHandler(filters.TEXT & ~filters.COMMAND, admin_handle_add_channel),
|
803 |
+
CommandHandler("start", start),
|
804 |
+
CommandHandler("cancel", cancel)
|
805 |
+
],
|
806 |
+
LIST_REMOVE_CHANNELS: [
|
807 |
+
CallbackQueryHandler(admin_handle_remove_channel, pattern='^remove_channel_'),
|
808 |
+
CommandHandler("start", start),
|
809 |
+
CommandHandler("cancel", cancel)
|
810 |
+
]
|
811 |
+
},
|
812 |
+
fallbacks=[CommandHandler("cancel", cancel), CommandHandler("start", start)],
|
813 |
+
allow_reentry=True
|
814 |
+
)
|
815 |
+
|
816 |
+
application.add_handler(conv_handler)
|
817 |
+
application.add_error_handler(error_handler)
|
818 |
+
print("Telegram bot Application initialized.")
|
819 |
+
|
820 |
+
@app.route("/")
|
821 |
+
async def index():
|
822 |
+
return jsonify({"status": "ok", "message": "Telegram bot is running."})
|
823 |
+
|
824 |
+
@app.route("/webhook", methods=["POST"])
|
825 |
+
async def webhook():
|
826 |
+
await setup_bot()
|
827 |
+
update = Update.de_json(request.get_json(force=True), application.bot)
|
828 |
+
await application.process_update(update)
|
829 |
+
return "ok"
|
830 |
+
|
831 |
+
@app.route("/set_webhook", methods=["GET"])
|
832 |
+
async def set_webhook_route():
|
833 |
+
await setup_bot()
|
834 |
+
webhook_url = os.getenv("WEBHOOK_URL")
|
835 |
+
if not webhook_url:
|
836 |
+
return jsonify({"status": "error", "message": "WEBHOOK_URL environment variable not set."}), 500
|
837 |
+
|
838 |
+
if not webhook_url.endswith("/webhook"):
|
839 |
+
webhook_url = f"{webhook_url.rstrip('/')}/webhook"
|
840 |
+
|
841 |
+
try:
|
842 |
+
await application.bot.set_webhook(url=webhook_url)
|
843 |
+
return jsonify({"status": "success", "message": f"Webhook set to {webhook_url}"})
|
844 |
+
except Exception as e:
|
845 |
+
return jsonify({"status": "error", "message": f"Failed to set webhook: {e}"}), 500
|
846 |
+
|
847 |
+
if __name__ == "__main__":
|
848 |
+
print("Starting Flask app...")
|
849 |
+
app.run(host='0.0.0.0', port=int(os.environ.get("PORT", 7860)))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
850 |
�
|