123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184 |
- #!/usr/bin/env python3
- """
- First, a few callback functions are defined. Then, those functions are passed to
- the Dispatcher and registered at their respective places.
- Then, the bot is started and runs until we press Ctrl-C on the command line.
- Usage:
- Example of a bot-user conversation using ConversationHandler.
- Send /start to initiate the conversation.
- Press Ctrl-C on the command line or send a signal to the process to stop the
- bot.
- """
- import logging
- from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update
- from telegram.ext import (
- Updater,
- CommandHandler,
- MessageHandler,
- Filters,
- ConversationHandler,
- CallbackContext,
- )
- from bs4 import BeautifulSoup
- import requests
- import json
- import os
- agent = 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) \
- Gecko/20100101 Firefox/24.0'
- headers = {'User-Agent': agent}
- base = "https://www.azlyrics.com/"
- def lyrics(artist, song):
- artist = artist.lower().replace(" ", "")
- song = song.lower().replace(" ", "")
- url = base+"lyrics/"+artist+"/"+song+".html"
- req = requests.get(url, headers=headers)
- soup = BeautifulSoup(req.content, "html.parser")
- lyrics = soup.find_all("div", attrs={"class": None, "id": None})
- if not lyrics:
- return {'Error': 'Unable to find '+song+' by '+artist}
- elif lyrics:
- lyrics = [x.getText() for x in lyrics]
- lyrics=str(lyrics)
- lyrics=lyrics.replace('["', "")
- lyrics=lyrics.replace('"]', "")
- lyrics=lyrics.replace("\\n", "\n")
- lyrics=lyrics.replace("\\r", "\r")
- lyrics=lyrics.replace("\'", "'")
- # return req
- return lyrics
- def lyric2list(text):
- text_list=[]
- lines_list=text.split("\n")
- lines=""
- lines_test=""
- for i in lines_list:
- lines_test=lines_test+i+"\n"
- if len(lines_test)>4096:
- lines_test=""
- text_list.append(lines)
- # print(lines)
- lines=i+"\n"
- lines_test=i+"\n"
- else:
- lines=lines+i+"\n"
- text_list.append(lines)
- return text_list
- # Enable logging
- logging.basicConfig(
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
- )
- logger = logging.getLogger(__name__)
- ARTST, SONG = range(2)
- def start(update, context):
- context.bot.send_message(chat_id=update.effective_chat.id, text=""" hi, i'm find_lyric bot
- it can find lyric by song name and the artist
- use /get to find lyric
- """)
- def get_lyric(update: Update, context: CallbackContext) -> int:
- user = update.message.from_user
- update.message.reply_text(' artist name:')
- return ARTST
- def artst(update: Update, context: CallbackContext) -> int:
- user = update.message.from_user
- text = update.message.text
- context.user_data['artst'] = text
- update.message.reply_text('song name:')
- return SONG
- def song(update: Update, context: CallbackContext) -> int:
- user = update.message.from_user
- text = update.message.text
- context.user_data['song'] = text
- user_data = context.user_data
- lyric=lyrics(user_data['artst'], user_data['song'])
- if len(lyric)<4096:
- update.message.reply_text(lyric)
- else:
- lyric_list=lyric2list(lyric)
- for i in lyric_list:
- update.message.reply_text(i)
- user_data.clear()
- # return DONE
- return ConversationHandler.END
- #def done(update: Update, context: CallbackContext) -> int:
- # return ConversationHandler.END
- def cancel(update: Update, context: CallbackContext) -> int:
- update.message.reply_text(
- 'Bye! I hope we can talk again some day.', )
- return ConversationHandler.END
- def main() -> None:
- # Create the Updater and pass it your bot's token.
- try:
- telegram_token=os.environ["TELEGRAM_TOKEN"]
- webhook_url = os.environ["WEBHOOK_URL"]
- except Exception as e:
- print("cant find "+str(e)+" environmant")
- exit()
- updater = Updater(token=telegram_token, use_context=True)
- # Get the dispatcher to register handlers
- dispatcher = updater.dispatcher
- start_handler = CommandHandler('start', start)
- dispatcher.add_handler(start_handler)
- # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
- conv_handler = ConversationHandler(
- entry_points=[CommandHandler('get', get_lyric)],
- states={
- ARTST: [MessageHandler(Filters.text & ~Filters.command, artst)],
- SONG: [MessageHandler(Filters.text & ~Filters.command, song)],
- },
- fallbacks=[CommandHandler('cancel', cancel)],
- )
- dispatcher.add_handler(conv_handler)
- # Start the Bot
- updater.start_webhook(listen="0.0.0.0",
- port=int(os.environ.get('PORT', 5000)),
- url_path=telegram_token)
- updater.bot.setWebhook(webhook_url + telegram_token)
- # Run the bot until you press Ctrl-C or the process receives SIGINT,
- # SIGTERM or SIGABRT. This should be used most of the time, since
- updater.idle()
- if __name__ == '__main__':
- main()
|