Python Spotify dinlenme botu yapımı

Fełix

Katılımcı Üye
7 Ocak 2023
361
2
214
NightmareTales
Python:
from uuid import uuid4

import os, urllib.request, logging, json, sys, auth
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler
from telegram import InputTextMessageContent, InlineQueryResultArticle

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

logger = logging.getLogger(__name__)

def help(bot, update):
    print ("Help page selected")
    bot.sendMessage(update.message.chat_id, text = "To search for a song on Spotify, just call the bot by typing @spotify_telegram_bot and then typing your query. Then, just select what category you would like to search under!")

def about(bot, update):
    print ("About page selected")
    bot.sendMessage(update.message.chat_id, text = "This bot has been created by GMCtree using Python and the Python Telegram Bot API created by the Python-Telegram-Bot Team")

def get_thumbnail(response):
    # check if images exist for search query
    if 'images' in response and len(response['images']) > 0:
        image = response['images'][0]
        thumbnail = image['url']
        thumbnail_width = image['width']
        thumbnail_height = image['height']
        return (thumbnail, thumbnail_width, thumbnail_height)
    else:
        return (None, None, None)

def search(query, query_type, auth_token):
    # replace all spaces with %20 as per Spotify Web API
    search_query = query.lower().strip().replace(" ", "%20")
    api_base_url = "https://api.spotify.com/v1/search?q="
    search_types = {
        "track" : api_base_url + search_query + "&type=track&limit=1",
        "artist" : api_base_url + search_query + "&type=artist&limit=1",
        "album" : api_base_url + search_query + "&type=album&limit=1",
        "playlist" : api_base_url + search_query + "&type=playlist&limit=1"
    }

    search_url = search_types[query_type]

    request = urllib.request.Request(search_url)
    request.add_header("Authorization", "Bearer " + auth_token)

    try:
        content_data = json.loads(urllib.request.urlopen(request).read())
    except urllib.error.HTTPError as err:
        if err.code == 400:
            print("Looks like you have a bad request. Have you checked to make sure your header is correct?")
            print(err.read())
        elif err.code == 401:
            print("Your authorization token is incorrect or expired. Please request a new one")
            print(err.read())
        else:
            print(err.read())

    if len(content_data[query_type + 's']['items']) == 0:
        return None
    else:
        response = content_data[query_type + 's']['items'][0]
        return response

def is_empty_query(query):
    return True if query == '' else False

def check_no_results(results):
    return True if len(results) == 0 else False

def build_inline_query_result_article(_type, response):
    (thumb_url, thumb_width, thumb_height) = (None, None, None)
    # use the album art of the track for the thumbnail
    if _type == 'Track':
        (thumb_url, thumb_width, thumb_height) = get_thumbnail(response['album'])
    else:
        (thumb_url, thumb_width, thumb_height) = get_thumbnail(response)

    spotify_link = response['external_urls']['spotify']
    name = response['name']
    query_result_article = InlineQueryResultArticle(id=uuid4(),
                        title=_type + ' - ' + name,
                        input_message_content=InputTextMessageContent(spotify_link),
                        thumb_url=thumb_url,
                        thumb_width=thumb_width,
                        thumb_height=thumb_height)

    return query_result_article

# main function to handle all inline queries
def inlinequery(bot, update):

    print("New query started")
    query = update.inline_query.query
    results = list()
    types = ['Track', 'Artist', 'Album', 'Playlist']

    auth_token = auth.get_auth_token()

    # if empty query, return blank results to prevent unnecessary Spotify API calls
    if is_empty_query(query):
        return results
    else:
    # each new value will show up in the response to the user
        for _type in types:
            response = search(query, _type.lower(), auth_token)
            if response is not None:
                results.append(build_inline_query_result_article(_type, response))

    # if there are no results, tell user
    if check_no_results(results):
        results.append(InlineQueryResultArticle(id=uuid4(),
                title="No results found",
                input_message_content=InputTextMessageContent("No results found")))

    update.inline_query.answer(results)

def error(bot, update, error):
   logger.warn('Update "%s" caused error "%s"' % (update, error))

# main function needed to enable logging
def main():

    # Check to see which environment to use by reading from config file
    with open("config.json", "r") as config_file:
        config = json.load(config_file)
        if not config["prod"]:
            with open("telegram_token.json", "r") as token_file:
                token = json.load(token_file)["token"]
        else:
            token = os.environ["TELEGRAM_KEY"]

    updater = Updater(token)

    dp = updater.dispatcher

    dp.add_handler(CommandHandler("help", help))

    dp.add_handler(CommandHandler("about", about))

    dp.add_handler(InlineQueryHandler(inlinequery))

    dp.add_error_handler(error)

    # begin long polling
    updater.start_polling()

    updater.idle()


if __name__ == '__main__':
    print ("Bot is running...")
    main()

Python:
# **********************************************************************************
# Spotify_Handle V0.01
# By:Ben Bellerose
# Description: This program handles all spotify interaction for the application.
# Reference: https://github.com/drshrey/spotify-flask-auth-example
# **********************************************************************************
# Modified from the original version above!

import json
import requests
import base64
import urllib
from flask import request
import logging
from utils import Utils
logger = logging.getLogger("Queue_Bot")

data = Utils.load_settings()

# Client Keys
CLIENT_ID = data['spotify']['CLIENT_ID']
CLIENT_SECRET = data['spotify']['CLIENT_SECRET']
history = data['history']['enabled']
playlist_id = data['history']['playlist_id']

# Spotify URLS
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_API_BASE_URL = "https://api.spotify.com"
API_VERSION = "v1"
SPOTIFY_API_URL = "{}/{}".format(SPOTIFY_API_BASE_URL, API_VERSION)

# Server-side Parameters
CLIENT_SIDE_URL = "http://127.0.0.1"
PORT = 8080
REDIRECT_URI = "{}:{}/callback/q".format(CLIENT_SIDE_URL, PORT)
SCOPE = "user-modify-playback-state playlist-modify-public playlist-modify-private user-read-currently-playing"
STATE = ""
SHOW_DIALOG_bool = True
SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()
refresh_token = None
authorization_header = None

# Authorization of application with spotify


def app_Authorization():
  auth_query_parameters = {
      "response_type": "code",
      "redirect_uri": REDIRECT_URI,
      "scope": SCOPE,
      "client_id": CLIENT_ID
  }
  url_args = "&".join(["{}={}".format(key, val)
                       for key, val in auth_query_parameters.items()])
  auth_url = "{}/?{}".format(SPOTIFY_AUTH_URL, url_args)
  return auth_url


def user_Authorization():
  global refresh_token, authorization_header
  auth_token = request.args['code']
  code_payload = {
      "grant_type": "authorization_code",
      "code": str(auth_token),
      "redirect_uri": REDIRECT_URI
  }
  base64encoded = base64.b64encode("{}:{}".format(
      CLIENT_ID, CLIENT_SECRET).encode('utf-8'))
  headers = {"Authorization": "Basic {}".format(
      base64encoded.decode('utf-8'))}
  post_request = requests.post(
      SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)

  # Tokens are Returned to Application
  response_data = json.loads(post_request.text)
  access_token = response_data["access_token"]
  refresh_token = response_data["refresh_token"]
  token_type = response_data["token_type"]
  expires_in = response_data["expires_in"]

  # Use the access token to access Spotify API
  authorization_header = {
      "Authorization": "Bearer {}".format(access_token)}
  return authorization_header


def refresh():
  global authorization_header
  code_payload = {
      "grant_type": "refresh_token",
      "refresh_token": str(refresh_token)
  }
  base64encoded = base64.b64encode("{}:{}".format(
      CLIENT_ID, CLIENT_SECRET).encode('utf-8'))
  headers = {"Authorization": "Basic {}".format(
      base64encoded.decode('utf-8'))}
  post_request = requests.post(
      SPOTIFY_TOKEN_URL, data=code_payload, headers=headers)

  logger.info(post_request.text)

  # Tokens are Returned to Application
  response_data = json.loads(post_request.text)
  access_token = response_data["access_token"]
  token_type = response_data["token_type"]
  expires_in = response_data["expires_in"]

  authorization_header = {
      "Authorization": "Bearer {}".format(access_token)}
  return authorization_header


def add_song_to_queue(uri):
  url = 'https://api.spotify.com/v1/me/player/queue?uri={id}'.format(id=uri)
  result = process_request(url, 'post')
  logger.debug(result.text)
  if result.status_code == 204:
    global history
    if history:
      add_to_history(uri)
    track_req = get_track_info(uri)
    json_obj = track_req.json()
    artists = ', '.join(artists['name']
                        for artists in json_obj['artists'])
    song_name = json_obj['name']
    data = {
        'song': song_name,
        'artists': artists,
        'uri': uri
    }
    return data
  return


def add_to_history(uri):
  global playlist_id
  url = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks?uris={uri}'
  result = process_request(url, 'post')
  logger.debug(result.text)
  return result


def get_track_info(uri):
  url = 'https://api.spotify.com/v1/tracks/{id}'
  id = uri.split(':')[-1]
  return process_request(url.format(id=id), 'get')


def get_song_and_artist(uri):
  track_req = get_track_info(uri)
  json_obj = track_req.json()
  logger.debug(json_obj)
  artists = ', '.join(artists['name']
                      for artists in json_obj['artists'])
  song_name = json_obj['name']
  logger.debug('here')
  return song_name, artists


def get_current_song():
  url = 'https://api.spotify.com/v1/me/player/currently-playing'
  response = process_request(url, 'get')
  if response.status_code == 200:
    try:
      response_json = response.json()
      song_title = response_json['item']['name']
      artists_json = response_json['item']['artists']
      artists = ', '.join(artists['name']
                          for artists in artists_json)
      logger.debug(f'Found {song_title} by {artists}')
      return song_title, artists
    except Exception as e:
      logger.debug(str(e))
  else:
    logger.debug(response)

  return None


def process_request(url, request_type):
  global authorization_header
  logger.info('Processing {} request {}'.format(request_type, url))
  if request_type == 'post':
    spotify_request = requests.post
  elif request_type == 'get':
    spotify_request = requests.get
  else:
    spotify_request = requests.put
  result = spotify_request(url, headers=authorization_header)
  return result

Yardım İçerikli Konuları THT Yardım Merkezinde Aça Bilirsiniz İyi Günler.
 
Üst

Turkhackteam.org internet sitesi 5651 sayılı kanun’un 2. maddesinin 1. fıkrasının m) bendi ile aynı kanunun 5. maddesi kapsamında "Yer Sağlayıcı" konumundadır. İçerikler ön onay olmaksızın tamamen kullanıcılar tarafından oluşturulmaktadır. Turkhackteam.org; Yer sağlayıcı olarak, kullanıcılar tarafından oluşturulan içeriği ya da hukuka aykırı paylaşımı kontrol etmekle ya da araştırmakla yükümlü değildir. Türkhackteam saldırı timleri Türk sitelerine hiçbir zararlı faaliyette bulunmaz. Türkhackteam üyelerinin yaptığı bireysel hack faaliyetlerinden Türkhackteam sorumlu değildir. Sitelerinize Türkhackteam ismi kullanılarak hack faaliyetinde bulunulursa, site-sunucu erişim loglarından bu faaliyeti gerçekleştiren ip adresini tespit edip diğer kanıtlarla birlikte savcılığa suç duyurusunda bulununuz.