find_lyrics 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env python3
  2. """
  3. First, a few callback functions are defined. Then, those functions are passed to
  4. the Dispatcher and registered at their respective places.
  5. Then, the bot is started and runs until we press Ctrl-C on the command line.
  6. Usage:
  7. Example of a bot-user conversation using ConversationHandler.
  8. Send /start to initiate the conversation.
  9. Press Ctrl-C on the command line or send a signal to the process to stop the
  10. bot.
  11. """
  12. import logging
  13. from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
  14. from telegram.ext import (
  15. Updater,
  16. CommandHandler,
  17. MessageHandler,
  18. Filters,
  19. ConversationHandler,
  20. CallbackContext,
  21. )
  22. from bs4 import BeautifulSoup
  23. import requests
  24. import json
  25. import os
  26. agent = 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) \
  27. Gecko/20100101 Firefox/24.0'
  28. headers = {'User-Agent': agent}
  29. base = "https://www.azlyrics.com/"
  30. def lyrics(artist, song):
  31. artist = artist.lower().replace(" ", "")
  32. song = song.lower().replace(" ", "")
  33. url = base+"lyrics/"+artist+"/"+song+".html"
  34. req = requests.get(url, headers=headers)
  35. soup = BeautifulSoup(req.content, "html.parser")
  36. lyrics = soup.find_all("div", attrs={"class": None, "id": None})
  37. if not lyrics:
  38. return {'Error': 'Unable to find '+song+' by '+artist}
  39. elif lyrics:
  40. lyrics = [x.getText() for x in lyrics]
  41. lyrics=str(lyrics)
  42. lyrics=lyrics.replace('["', "")
  43. lyrics=lyrics.replace('"]', "")
  44. lyrics=lyrics.replace("\\n", "\n")
  45. lyrics=lyrics.replace("\\r", "\r")
  46. lyrics=lyrics.replace("\'", "'")
  47. # return req
  48. return lyrics
  49. def lyric2list(text):
  50. text_list=[]
  51. lines_list=text.split("\n")
  52. lines=""
  53. lines_test=""
  54. for i in lines_list:
  55. lines_test=lines_test+i+"\n"
  56. if len(lines_test)>4096:
  57. lines_test=""
  58. text_list.append(lines)
  59. # print(lines)
  60. lines=i+"\n"
  61. lines_test=i+"\n"
  62. else:
  63. lines=lines+i+"\n"
  64. text_list.append(lines)
  65. return text_list
  66. # Enable logging
  67. logging.basicConfig(
  68. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
  69. )
  70. logger = logging.getLogger(__name__)
  71. ARTST, SONG = range(2)
  72. def start(update, context):
  73. context.bot.send_message(chat_id=update.effective_chat.id, text=""" hi, i'm find_lyric bot
  74. it can find lyric by song name and the artist
  75. use /get to find lyric
  76. """)
  77. def get_lyric(update: Update, context: CallbackContext) -> int:
  78. user = update.message.from_user
  79. update.message.reply_text(' artist name:')
  80. return ARTST
  81. def artst(update: Update, context: CallbackContext) -> int:
  82. user = update.message.from_user
  83. text = update.message.text
  84. context.user_data['artst'] = text
  85. update.message.reply_text('song name:')
  86. return SONG
  87. def song(update: Update, context: CallbackContext) -> int:
  88. user = update.message.from_user
  89. text = update.message.text
  90. context.user_data['song'] = text
  91. user_data = context.user_data
  92. lyric=lyrics(user_data['artst'], user_data['song'])
  93. if len(lyric)<4096:
  94. update.message.reply_text(lyric)
  95. else:
  96. lyric_list=lyric2list(lyric)
  97. for i in lyric_list:
  98. update.message.reply_text(i)
  99. user_data.clear()
  100. # return DONE
  101. return ConversationHandler.END
  102. #def done(update: Update, context: CallbackContext) -> int:
  103. # return ConversationHandler.END
  104. def cancel(update: Update, context: CallbackContext) -> int:
  105. update.message.reply_text(
  106. 'Bye! I hope we can talk again some day.', )
  107. return ConversationHandler.END
  108. def main() -> None:
  109. # Create the Updater and pass it your bot's token.
  110. try:
  111. telegram_token=os.environ["TELEGRAM_TOKEN"]
  112. webhook_url = os.environ["WEBHOOK_URL"]
  113. except Exception as e:
  114. print("cant find "+str(e)+" environmant")
  115. exit()
  116. updater = Updater(token=telegram_token, use_context=True)
  117. # Get the dispatcher to register handlers
  118. dispatcher = updater.dispatcher
  119. start_handler = CommandHandler('start', start)
  120. dispatcher.add_handler(start_handler)
  121. # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
  122. conv_handler = ConversationHandler(
  123. entry_points=[CommandHandler('get', get_lyric)],
  124. states={
  125. ARTST: [MessageHandler(Filters.text & ~Filters.command, artst)],
  126. SONG: [MessageHandler(Filters.text & ~Filters.command, song)],
  127. },
  128. fallbacks=[CommandHandler('cancel', cancel)],
  129. )
  130. dispatcher.add_handler(conv_handler)
  131. # Start the Bot
  132. updater.start_webhook(listen="0.0.0.0",
  133. port=int(os.environ.get('PORT', 5000)),
  134. url_path=telegram_token)
  135. updater.bot.setWebhook(webhook_url + telegram_token)
  136. # Run the bot until you press Ctrl-C or the process receives SIGINT,
  137. # SIGTERM or SIGABRT. This should be used most of the time, since
  138. updater.idle()
  139. if __name__ == '__main__':
  140. main()