Advertisement
Guest User

Untitled

a guest
Dec 7th, 2024
26
0
155 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.89 KB | Software | 0 0
  1. from telethon import TelegramClient, events
  2. from telethon import errors
  3.  
  4. from telethon.tl.custom import Button
  5.  
  6. from telethon.errors.rpcerrorlist import FloodWaitError
  7.  
  8. import logger
  9. from logger import CMDColorLogger, cmd_message_colorized
  10.  
  11. import asyncio
  12. import os, re, sys
  13. import config
  14.  
  15. import muzfondsaver
  16. from muzfondsaver import MuzofondMusicSaver
  17.  
  18. import functions
  19. import logging, tracemalloc
  20.  
  21.  
  22. is_downloaded = False
  23.  
  24. msg_ids = []
  25.  
  26.  
  27. def start_bot(start=True):
  28.     client = TelegramClient(
  29.         config.SESSION_NAME,
  30.         config.API_ID,
  31.         config.API_HASH
  32.     )
  33.     if start:
  34.         client.start(bot_token=config.PrincessElsaAIBot_BOT_TOKEN)
  35.  
  36.     return client
  37.  
  38.  
  39. def main():
  40.     try:
  41.         # if not session created
  42.         if not (f'{config.SESSION_NAME}.session' in os.listdir(f'{config.THIS_SCRIPT_DIR}')):
  43.             cmd_message_colorized(CMDColorLogger(), 'Session created...', config.MAGENTA)
  44.             client = start_bot()
  45.             cmd_message_colorized(CMDColorLogger(), f'Bot started', config.MAGENTA)
  46.        
  47.         if (f'{config.SESSION_NAME}.session' in os.listdir(f'{config.THIS_SCRIPT_DIR}')):
  48.             cmd_message_colorized(CMDColorLogger(), f'Bot started', config.MAGENTA)
  49.            
  50.             client = start_bot(start=False)
  51.            
  52.  
  53.             try:
  54.                 @client.on(events.NewMessage(pattern='/start'))
  55.                 async def respond_start(event):
  56.                     functions.append_msg_id(msg_ids, event.id)
  57.                     # cmd_message_colorized(CMDColorLogger(), f'/start: {msg_ids}', config.LIGHT_GREEN)
  58.  
  59.                     if config.send_name_button_event_was_triggered and not config.send_name_button_event_was_finished:    
  60.                         pass
  61.  
  62.                     if not config.send_name_button_event_was_triggered:
  63.                         user = await event.get_sender() # name = utils.get_display_name(sender) ?
  64.                        
  65.                         msg = await event.respond(
  66.                             f'Hello, {user.first_name} ☘️!\nThis bot will send 🎁 you a chosen song ' \
  67.                             '(mp3 file) from a songs list of an artist you chose ' \
  68.                             '🔊 (from muzofond.fm)',
  69.                             buttons=[
  70.                                 Button.inline('Click and send a music artist name...', b'send_name_button')
  71.                             ]
  72.                         )
  73.  
  74.                         functions.append_msg_id(msg_ids, msg.id)
  75.                         # cmd_message_colorized(CMDColorLogger(), f'/start: {msg_ids}', config.LIGHT_GREEN)
  76.  
  77.             except Exception as ex:
  78.                 cmd_message_colorized(CMDColorLogger(), f'Exception: respond_start: {ex}', config.RED)
  79.            
  80.  
  81.             try:
  82.                 @client.on(events.NewMessage(incoming=True, pattern='/delete'))
  83.                 async def delete_dialog(event):
  84.                     functions.append_msg_id(msg_ids, event.id)
  85.                     # cmd_message_colorized(CMDColorLogger(), f'/delete: {msg_ids}', config.LIGHT_GREEN)
  86.                    
  87.                     try:
  88.                         await client.delete_messages(event.chat_id, msg_ids)
  89.                         msg_ids.clear()
  90.                         # cmd_message_colorized(CMDColorLogger(), f'AFTER DELETING? /delete: {msg_ids}', config.LIGHT_GREEN)
  91.                     except Exception as ex:
  92.                         cmd_message_colorized(CMDColorLogger(), f'Exception: delete_messages: {ex}',config.RED)
  93.                                            
  94.             except Exception as ex:
  95.                 cmd_message_colorized(CMDColorLogger(), f'Exception: delete_messages: {ex}',config.RED)
  96.  
  97.  
  98.             # not /start and not /delete
  99.             try:
  100.                 @client.on(events.NewMessage(pattern=r'^((?!\/start|\/delete).)*$'))
  101.                 async def respond_else(event):
  102.                     functions.append_msg_id(msg_ids, event.id)
  103.                     # cmd_message_colorized(CMDColorLogger(), f'/start|/delete: {msg_ids}', config.LIGHT_GREEN)
  104.  
  105.                     if config.send_name_button_event_was_triggered and not config.send_name_button_event_was_finished:
  106.                         pass
  107.                    
  108.                     if not config.send_name_button_event_was_triggered:
  109.                         # append id ot the message of "pattern=r'^((?!\/start|\/delete).)*$'" itself
  110.                         msg = await event.respond('Try [/start](/start)...')                      
  111.                        
  112.                         functions.append_msg_id(msg_ids, msg.id)
  113.                         # cmd_message_colorized(CMDColorLogger(), f'/start|/delete): {msg_ids}', config.LIGHT_GREEN)
  114.                        
  115.             except Exception as ex:
  116.                 cmd_message_colorized(CMDColorLogger(), f'Exception: respond_else: {ex}', config.RED)
  117.  
  118.            
  119.             ##############################################################################
  120.             # button
  121.             ##############################################################################
  122.             @client.on(events.CallbackQuery(data=b'send_name_button'))
  123.             async def handler_send_name_button(event):
  124.                 # cmd_message_colorized(CMDColorLogger(), f'send_name_button: {msg_ids}', config.LIGHT_GREEN)
  125.  
  126.                 config.send_name_button_event_was_triggered = True
  127.                    
  128.                 msg = await event.respond(f'Type the name of a musician. After that the bot will' \
  129.                                           ' send the list of tracks of the chosen musician...' )
  130.  
  131.                 functions.append_msg_id(msg_ids, msg.id)
  132.                 # cmd_message_colorized(CMDColorLogger(), f'send_name_button: {msg_ids}', config.LIGHT_GREEN)
  133.                
  134.                 @client.on(events.NewMessage)
  135.                 async def handler_a_name_is_chosen_after_clicking_send_name_button(event):
  136.                     functions.append_msg_id(msg_ids, event.id)
  137.                     # cmd_message_colorized(CMDColorLogger(), f'handler_a_name_is_chosen_after_clicking_send_name_button: {msg_ids}', config.LIGHT_GREEN)
  138.  
  139.                     try:
  140.                         if config.send_name_button_event_was_triggered:
  141.                             artist = str(event.text).strip().title()
  142.                                          
  143.                             if not any(x.isalpha() for x in artist):
  144.                                 msg = await event.respond('Your musician\'s name didn\'t have any letters! Is it a joke? Try again with a real name...')
  145.                                 functions.append_msg_id(msg_ids, msg.id)
  146.                                 # cmd_message_colorized(CMDColorLogger(), f'handler_a_name_is_chosen_after_clicking_send_name_button: {msg_ids}', config.LIGHT_GREEN)
  147.  
  148.                             # elif (event.text != '/delete') and (event.text != '/start'):
  149.                             cmd_message_colorized(CMDColorLogger(), f'You chose {artist}', config.YELLOW)
  150.                                        
  151.                             mfs = MuzofondMusicSaver(artist)
  152.                             songs = mfs.get_mp3s_of_author_found_songs()
  153.                                
  154.                             if (not songs) or (songs == 'No such author') or (songs == 'Error finding links of songs'):
  155.                                 msg = await event.respond(f'🐖 Maybe there is no such author: *{artist}* on this site... 🆘. Try [/start](/start)')
  156.                                 functions.append_msg_id(msg_ids, msg.id)
  157.                                
  158.                                 # cmd_message_colorized(
  159.                                 #     CMDColorLogger(),
  160.                                 #     f'handler_a_name_is_chosen_after_clicking_send_name_button: {event.id} {msg.id}',
  161.                                 #     config.RED
  162.                                 # )
  163.                                
  164.                             else:
  165.                                 for song in songs:
  166.                                     mp3_title = song.split(":::")[1]
  167.                                     mp3_link = song.split(":::")[0]
  168.  
  169.                                     msg = await event.respond(
  170.                                         f'{artist}, [link]({mp3_link})',
  171.                                         buttons=[
  172.                                             Button.inline(
  173.                                                 f'🏆 {artist}: {mp3_title} 🐈',
  174.                                                 data=b'download mp3'
  175.                                             )
  176.                                         ]
  177.                                     )
  178.  
  179.                                     functions.append_msg_id(msg_ids, msg.id)
  180.                                     # cmd_message_colorized(CMDColorLogger(), f'handler_a_name_is_chosen_after_clicking_send_name_button: {msg_ids}', config.LIGHT_GREEN)
  181.  
  182.                             del mfs, songs
  183.  
  184.                         config.send_name_button_event_was_triggered = False
  185.                         config.send_name_button_event_was_finished = True
  186.  
  187.                     except Exception as ex:
  188.                         cmd_message_colorized(
  189.                             CMDColorLogger(),
  190.                             f'handler_a_name_is_chosen_after_clicking_send_name_button: {ex}',
  191.                             config.RED
  192.                         )
  193.  
  194.             @client.on(events.CallbackQuery(data=b'download mp3'))
  195.             async def handler_download(event):
  196.                 button_info = await event.get_message()
  197.                 chat = await event.get_input_chat() # bot chat
  198.                 user = await event.get_sender()
  199.                
  200.                 try:
  201.                     song_title = str(button_info.reply_markup.rows[0].buttons[0].text).split(': ')[1] # f'{artist}: {mp3_title}',
  202.                     artist = str(button_info.reply_markup.rows[0].buttons[0].text).split(': ')[0] # f'{artist}: {mp3_title}',
  203.                     song_url = str(button_info.entities[0].url)
  204.  
  205.                     # download a song
  206.                     try:
  207.                         filename = f'{artist} - {song_title}'
  208.                        
  209.                         msg = await event.respond(f'👺 {user.first_name}, 🐥 please wait a little... 🌈\n {filename} is being downloaded ⚙️ ...')
  210.                         functions.append_msg_id(msg_ids, msg.id)
  211.  
  212.                         cmd_message_colorized(CMDColorLogger(), f'Trying to download: {filename}.mp3...', config.LIGHT_GREEN)
  213.                        
  214.                         is_downloaded = functions.download_file(song_url, f'{config.THIS_SCRIPT_DIR}/sent_songs/{filename}.mp3')
  215.  
  216.                         if not is_downloaded:
  217.                             error_msg = await event.respond(f'⛔️ {user.first_name}, ⛔️ seems there is a problem downloading {filename}.')
  218.                             error_msg2 = await event.respond('Try later 🕐🕑🕒🕓🕔🕕 or [/start](/start) or [/delete](/delete)')
  219.                            
  220.                             functions.append_msg_id(msg_ids, error_msg.id)
  221.                             functions.append_msg_id(msg_ids, error_msg2.id)
  222.                        
  223.                         if is_downloaded:
  224.                             mfs = MuzofondMusicSaver(artist)
  225.                             mfs.clear_mp3_metadata(f'{config.THIS_SCRIPT_DIR}/sent_songs/{filename}.mp3')
  226.  
  227.                             cmd_message_colorized(CMDColorLogger(), f'The tags are deleted from {filename}.mp3...', config.LIGHT_GREEN)
  228.                            
  229.                             # SENDING THE CHOSEN FILE CLEARD FROM METADATA
  230.                             # TO THE USER
  231.                             msg = await event.respond(f'{user.first_name}, please wait a little... It\'s being processed 🕐')
  232.                             functions.append_msg_id(msg_ids, msg.id)
  233.                             await asyncio.sleep(4)
  234.                            
  235.                             msg = await event.respond(f'{user.first_name}, Still being processed... 🕑')
  236.                             functions.append_msg_id(msg_ids, msg.id)
  237.                             await asyncio.sleep(4)
  238.                            
  239.                             msg = await event.respond(f'{user.first_name}, Don\'t panic, if you see this message - it\'s still being processed... 🕒')
  240.                             functions.append_msg_id(msg_ids, msg.id)
  241.                             await asyncio.sleep(4)
  242.                            
  243.                             msg = await event.respond(f'{user.first_name}, Just 10-15 seconds... It\'s being processed 🕓')
  244.                             functions.append_msg_id(msg_ids, msg.id)
  245.                             await asyncio.sleep(4)
  246.                            
  247.                             msg = await event.respond(f'{user.first_name}, A little patience... It\'s STILL being processed 🕔')
  248.                             functions.append_msg_id(msg_ids, msg.id)
  249.                             await asyncio.sleep(4)
  250.                            
  251.                             msg = await event.respond(f'{user.first_name}, Yes! It\'s STILL being processed 🕕')
  252.                             functions.append_msg_id(msg_ids, msg.id)
  253.  
  254.                             # sending file
  255.                             file = await client.upload_file(f'{config.THIS_SCRIPT_DIR}/sent_songs/{filename}.mp3')
  256.                            
  257.                             await client.send_file(chat, file)
  258.  
  259.                             msg = await client.send_message(
  260.                                 chat,
  261.                                 f'🐥 Hey, {user.first_name}!\nHere\'s your song: {filename}'
  262.                             )
  263.                             functions.append_msg_id(msg_ids, msg.id)
  264.  
  265.                             cmd_message_colorized(
  266.                                 CMDColorLogger(),
  267.                                 f'The song {filename}.mp3 is sent.',
  268.                                 config.LIGHT_GREEN
  269.                             )
  270.                      
  271.                     except Exception as ex:
  272.                         cmd_message_colorized(CMDColorLogger(), f'Exception: download_file or clear_mp3_metadata: {ex}',config.RED)
  273.                
  274.                 except Exception as ex:
  275.                     cmd_message_colorized(CMDColorLogger(), f'Exception @client.on(events.CallbackQuery(data=b\'mp3\')): {ex}', config.RED)
  276.  
  277.  
  278.             with client:
  279.                 client.run_until_disconnected()
  280.  
  281.  
  282.     except Exception as ex:
  283.         cmd_message_colorized(CMDColorLogger(), f'Exception: {ex}', config.RED)
  284.     except errors.FloodWaitError as ex:
  285.         cmd_message_colorized(CMDColorLogger(), f'Have to sleep: {ex.seconds}', config.RED)
  286.         asyncio.sleep(ex.seconds)
  287.  
  288.        
  289.  
  290. if __name__ == '__main__':
  291.     main()
  292.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement