Exemplo n.º 1
0
 def login(self, login=None, password=None):
     if self.conf.get_attr("token") is not False:
         client = Client().from_token(self.conf.get_attr("token"))
     elif login is not None and password is not None:
         client = Client().from_credentials(login, password)
         token = client.token
         self.conf.set_attr("token", token)
     else:
         client = Client()
     self.client = client
     return client
Exemplo n.º 2
0
 def init(self):
     
     if os.path.isfile('token.txt'):
         try:
             tokenFile = open('token.txt', 'r')
             self.token = tokenFile.read()
             tokenFile.close();
             self.client = Client(self.token)
             self.loggedIn = True
         except:
             print("Failed to create client using saved token. Enter your login/password.")
             self.login()
             
     else:
         self.login()
Exemplo n.º 3
0
    def init(self):
        if os.path.isfile('token.txt'):
            try:
                tokenFile = open('token.txt', 'r')
                self.token = tokenFile.read()
                tokenFile.close()
                self.client = Client(self.token)
                self.loggedIn = True
                self.online = True
            except:
                return False

        else:
            return False

        return True
	def getNameTrack(self):
		'''Grab liked tracks from Yandex Music and create list of tracks and artists'''
		client = Client()
		client = Client.from_credentials(self.userYaLogin, self.userYaPassword)

		listLikesTacks = []
	
		listIDLikesTacks = client.users_likes_tracks().tracksIds #List of tracks ID 
	
		for ids in listIDLikesTacks:
			try:
				songName = client.tracks([ids])[0]['title']
				singerName = client.tracks([ids])[0]['artists'][0]['name']
				track_info = []
				track_info.append(songName)
				track_info.append(singerName)
				listLikesTacks.append(track_info)
				print('ID: 'ids)
			except:
				print('Founed error with ID:', ids)
				pass

		return listLikesTacks
Exemplo n.º 5
0
    async def yaplay(self, ctx, arg: str = None):
        if arg == None:
            if await MusicBot.langueg(ctx) == "RUS":
                embed = discord.Embed(
                    title=f"Вы должны указать название трэка", color=0xff7606)
            elif await MusicBot.langueg(ctx) == "ENG":
                embed = discord.Embed(
                    title=f"You must indicate the name of the track.",
                    color=0xff7606)
            await ctx.send(embed=embed)
            return
        vol = 50
        self.vol = vol
        voice = get(self.bot.voice_clients, guild=ctx.guild)
        try:
            channel = ctx.author.voice.channel
        except:
            if await MusicBot.langueg(ctx) == "RUS":
                embed = discord.Embed(
                    title=f"**{ctx.author.name} Вы не в голосовом канале**",
                    color=0xff7606)
            elif await MusicBot.langueg(ctx) == "ENG":
                embed = discord.Embed(
                    title=
                    f"**{ctx.author.name} You are not in the voice channel**",
                    color=0xff7606)
            await ctx.send(embed=embed)
            return

        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()

        #Логирование (отключение)
        logger = logging.getLogger()
        logger.setLevel(logging.CRITICAL)

        #Подключенеи к акку
        request = Request(proxy_url="https://*****:*****@217.29.62.232:6333")
        client = Client(token=MusicBot.YANDEX_TOKEN, request=request)

        #Делаем поисковой запрос
        search = client.search(arg)

        #Получаем треки
        tracks = search.tracks

        #Сортируем треки в list
        results = tracks.results

        #Получаем первый трек
        track = results[0]

        #Получаем всю инфу по загрузке
        info = track.get_download_info(get_direct_links=True)
        #get_direct_links=True - обязательно надо, а то х*йня получается!!!!!!!!!

        try:
            #Получаем полный путь к музыкальному файлу (поток)
            self.playurl = info[0].direct_link
            self.voice = voice

            self.voice.play(discord.FFmpegPCMAudio(self.playurl))

            self.voice.source = discord.PCMVolumeTransformer(voice.source)
            self.voice.source.volume = self.vol
        except:
            if await MusicBot.langueg(ctx) == "RUS":
                embed = discord.Embed(
                    title=
                    f"**{ctx.author.name} На данный момент песня уже играет**",
                    color=0xff7606)
            elif await MusicBot.langueg(ctx) == "ENG":
                embed = discord.Embed(
                    title=
                    f"**{ctx.author.name} At the moment the song is already playing**",
                    color=0xff7606)
            await ctx.send(embed=embed)
            return
        #Вызываем плеер

        if await MusicBot.langueg(ctx) == "RUS":
            embed = discord.Embed(
                title=f"**{track.title}**",
                description=
                f":white_small_square: **ID:  {track.id} :game_die:**\n\n"
                f":white_small_square: **Регион: {track.regions[0]} :globe_with_meridians:**\n\n"
                f":white_small_square: **[Поделится](https://music.yandex.ru/track/{track.id}) :trumpet:**\n\n",
                color=0xf2a20d)
            # ~ embed.set_thumbnail(url=f"{cover_uri}")
            # ~ embed.set_image(url=f'{track.og_image}')
            embed.set_thumbnail(
                url=
                f"https://cdn.dribbble.com/users/851627/screenshots/2270820/record-player.gif"
            )

            embed.set_footer(
                text=
                f"•Длительность трека: {int((track.duration_ms)/1000/60)} минут\n•Исполнитель: {track.artists[0].name}"
            )
        elif await MusicBot.langueg(ctx) == "ENG":
            embed = discord.Embed(
                title=f"**{track.title}**",
                description=
                f":white_small_square: **ID:  {track.id} :game_die:**\n\n"
                f":white_small_square: **Region: {track.regions[0]} :globe_with_meridians:**\n\n"
                f":white_small_square: **[Share](https://music.yandex.ru/track/{track.id}) :trumpet:**\n\n",
                color=0xf2a20d)
            # ~ embed.set_thumbnail(url=f"{cover_uri}")
            # ~ embed.set_image(url=f'{track.og_image}')
            embed.set_thumbnail(
                url=
                f"https://cdn.dribbble.com/users/851627/screenshots/2270820/record-player.gif"
            )

        msg = await ctx.send(embed=embed)

        await msg.add_reaction(str("▶"))
        await msg.add_reaction(str("⏸"))
        await msg.add_reaction(str("🔊"))
        await msg.add_reaction(str("🔉"))
        await msg.add_reaction(str("⏹"))
        await msg.add_reaction(str("❤️"))
        self.msg_play = msg
Exemplo n.º 6
0
        await ctx.voice_client.disconnect()

    @play.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("Вы не подключены к голосовому каналу.")
                raise commands.CommandError(
                    "Author not connected to a voice channel.")


bot = commands.Bot(command_prefix=commands.when_mentioned_or("m."),
                   description='Relatively simple music bot example')


@bot.event
async def on_ready():
    print('Logged in as {0} ({0.id})'.format(bot.user))
    print('------')


if cfg['YANDEX'].getboolean('use_token'):
    client = Client(cfg['YANDEX']['token'])
else:
    client = Client.from_credentials(cfg['YANDEX']['login'],
                                     cfg['YANDEX']['password'])
bot.add_cog(Music(bot))
bot.run(cfg['DISCORD']['token'])
Exemplo n.º 7
0
from yandex_music.client import Client

client = Client("your_token")
Exemplo n.º 8
0
 def logout(self):
     self.conf.remove_attr("token")
     self.client = Client()
     pass
Exemplo n.º 9
0
 def __init__(self):
     logger.level = logging.ERROR
     self.client = Client()
     self.cache = {}
     self.load_cache()
     self.i = 0
Exemplo n.º 10
0
            old_csv.columns[[0]],
            axis=1)  # удаляем получающуюся после импорта лишнюю колонку
        new_csv = pd.concat([old_csv, yandex_daily_avg],
                            ignore_index=True,
                            sort=False)
        new_csv.reset_index(inplace=True)
        new_csv.drop(new_csv.columns[[0]], axis=1, inplace=True)
        new_csv.to_csv("all_yandex.csv", encoding="utf-8")


# In[ ]:

# создаем словарь жанров
try:
    from yandex_music.client import Client
    client = Client()
    client = Client.from_credentials('*****@*****.**',
                                     'aintthateasy')

    gs = client.genres()

    keys = []
    values = []

    # создаем полный словарь
    for i in range(0, len(gs)):
        if len(gs[i].sub_genres) == 0:
            values.append(gs[i].titles["ru"]["title"])
            keys.append(gs[i].id)
        else:
            values.append(gs[i]["title"])
Exemplo n.º 11
0
def generate_token(credentials_file):
    login, password = get_login_and_password(credentials_file)
    return Client().generate_token_by_username_and_password(username=login, password=password)