예제 #1
0
파일: afk.py 프로젝트: maya143-1/Nolan_edit
async def type_afk_is_not_true(notafk):
    """ This sets your status as not afk automatically when you write something while being afk """
    global ISAFK
    global COUNT_MSG
    global USERS
    global AFKREASON
    global USER_AFK  # pylint:disable=E0602
    global afk_time  # pylint:disable=E0602
    global afk_start
    global afk_end
    user = await bot.get_me()
    last = user.last_name
    if last and last.endswith(" [ OFFLINE ]"):
        last1 = last[:-12]
    else:
        last1 = ""
    back_alive = datetime.now()
    afk_end = back_alive.replace(microsecond=0)
    if ISAFK:
        ISAFK = False
        msg = await notafk.respond("**I'm no longer AFK.**")
        time.sleep(3)
        await msg.delete()
        await notafk.client(
            UpdateProfileRequest(first_name=user.first_name, last_name=last1))
        if BOTLOG:
            await notafk.client.send_message(
                BOTLOG_CHATID,
                "You've recieved " + str(COUNT_MSG) + " messages from " +
                str(len(USERS)) + " chats while you were away",
            )
            for i in USERS:
                name = await notafk.client.get_entity(i)
                name0 = str(name.first_name)
                await notafk.client.send_message(
                    BOTLOG_CHATID,
                    "[" + name0 + "](tg://user?id=" + str(i) + ")" +
                    " sent you " + "`" + str(USERS[i]) + " messages`",
                )
        COUNT_MSG = 0
        USERS = {}
        AFKREASON = None
예제 #2
0
파일: off.py 프로젝트: ez69bw/ezbw
async def type_afk_is_not_true(notafk):
    """This sets your status as not afk automatically when you write something while being afk"""
    global ISAFK
    global COUNT_MSG
    global USERS
    global AFKREASON
    global USER_AFK  # pylint:disable=E0602
    global afk_time  # pylint:disable=E0602
    global afk_start
    global afk_end
    user = await bot.get_me()  # pylint:disable=E0602
    last = user.last_name
    if last and last.endswith("⧼ OFF ⧽"):
        last1 = last[:-12]
    else:
        last1 = ""
    back_alive = datetime.now()
    afk_end = back_alive.replace(microsecond=0)
    if ISAFK:
        ISAFK = False
        msg = await notafk.respond("**eyoo wassup y'all**")
        time.sleep(3)
        await msg.delete()
        await notafk.client(
            UpdateProfileRequest(first_name=user.first_name, last_name=last1))
        if BOTLOG:
            await notafk.client.send_message(
                BOTLOG_CHATID,
                "Anda Mendapatkan " + str(COUNT_MSG) + " Pesan Dari " +
                str(len(USERS)) + " Obrolan Saat Anda AFK",
            )
            for i in USERS:
                name = await notafk.client.get_entity(i)
                name0 = str(name.first_name)
                await notafk.client.send_message(
                    BOTLOG_CHATID,
                    "[" + name0 + "](tg://user?id=" + str(i) + ")" +
                    " Mengirim Mu " + "`" + str(USERS[i]) + " Pesan`",
                )
        COUNT_MSG = 0
        USERS = {}
        AFKREASON = None
예제 #3
0
def main():
    previous_time = None
    with TelegramClient(session_name, API_ID, API_HASH) as client:
        while True:
            try:
                curr_time = time_util.get_time()
                if previous_time != curr_time:
                    previous_time = curr_time
                    temp = time_util.time_progress()
                    image_util.draw_time(curr_time)

                    client(UpdateProfileRequest(about=temp))

                    image = client.upload_file(time_av)
                    client(DeletePhotosRequest(
                        client.get_profile_photos('me')))
                    client(UploadProfilePhotoRequest(image))
            except errors.FloodWaitError as er:
                print('Flood wait for ', er.seconds)
                time.sleep(int(er.seconds))
예제 #4
0
async def spotifybio(event):
    "Toggle Spotify Bio"
    if not await sp_var_check(event):
        return
    if SP_DATABASE.SPOTIFY_MODE:
        SP_DATABASE.SPOTIFY_MODE = False
        if USER_INITIAL_BIO:
            await catub(UpdateProfileRequest(about=USER_INITIAL_BIO["bio"]))
            USER_INITIAL_BIO.clear()
        await edit_delete(event, " `Spotify Bio disabled !`")
    else:
        await edit_delete(
            event,
            "✅ `Spotify Bio enabled` \nCurrent Spotify playback will updated in the Bio",
        )
        USER_INITIAL_BIO["bio"] = (
            (await catub(GetFullUserRequest(catub.uid))).full_user
        ).about or ""
        SP_DATABASE.SPOTIFY_MODE = True
        await spotify_bio()
예제 #5
0
async def _(ult):
    if not ult.out and not is_fullsudo(ult.sender_id):
        return await eod(ult, "`This Command Is Sudo Restricted.`")
    ok = await eor(ult, "...")
    names = ult.pattern_match.group(1)
    first_name = names
    last_name = ""
    if "//" in names:
        first_name, last_name = names.split("//", 1)
    try:
        await ult.client(
            UpdateProfileRequest(
                first_name=first_name,
                last_name=last_name,
            ), )
        await ok.edit(f"Name changed to `{names}`")
    except Exception as ex:
        await ok.edit("Error occured.\n`{}`".format(str(ex)))
    await asyncio.sleep(10)
    await ok.delete()
예제 #6
0
async def lastbio(lfmbio):
    "To Enable or Disable the last.fm current playing to bio"
    arg = lfmbio.pattern_match.group(1).lower()
    if arg == "on":
        setrecursionlimit(700000)
        if not LASTFM_.LASTFMCHECK:
            LASTFM_.LASTFMCHECK = True
            environ["errorcheck"] = "0"
            await lfmbio.edit(LFM_BIO_ENABLED)
            await sleep(4)
            await get_curr_track(lfmbio)
        else:
            await lfmbio.edit(LFM_BIO_RUNNING)
    elif arg == "off":
        LASTFM_.LASTFMCHECK = False
        LASTFM_.RUNNING = False
        await lfmbio.client(UpdateProfileRequest(about=DEFAULT_BIO))
        await lfmbio.edit(LFM_BIO_DISABLED)
    else:
        await lfmbio.edit(LFM_BIO_ERR)
예제 #7
0
async def lastbio(lfmbio):
    arg = lfmbio.pattern_match.group(1).lower()
    global LASTFMCHECK
    global RUNNING
    if arg == "on":
        setrecursionlimit(700000)
        if not LASTFMCHECK:
            LASTFMCHECK = True
            environ["errorcheck"] = "0"
            await lfmbio.edit(LFM_BIO_ENABLED)
            await sleep(4)
            await get_curr_track(lfmbio)
        else:
            await lfmbio.edit(LFM_BIO_RUNNING)
    elif arg == "off":
        LASTFMCHECK = False
        RUNNING = False
        await bot(UpdateProfileRequest(about=DEFAULT_BIO))
        await lfmbio.edit(LFM_BIO_DISABLED)
    else:
        await lfmbio.edit(LFM_BIO_ERR)
예제 #8
0
async def name(event):
    match = event.matches[0].group(1)
    if not match:
        me = await client.get_me()
        text = f"**First name:** `{me.first_name}`"
        if me.last_name:
            text += f"\n**Last name:** `{me.last_name}`"
        await event.edit(text)
        return

    split = match.split("last=")
    first = split[0] if split[0] else None
    last = split[1] if len(split) == 2 else None

    try:
        await client(UpdateProfileRequest(first_name=first, last_name=last))
        await event.edit("`Name was successfully changed.`")
    except FirstNameInvalidError:
        await event.edit("`The first name is invalid.`")
    except Exception as e:
        await event.reply('`' + type(e).__name__ + ': ' + str(e) + '`')
예제 #9
0
async def set_not_afkb(event):
    global USER_AFKB  # pylint:disable=E0602
    global afkb_time  # pylint:disable=E0602
    global last_afkb_message  # pylint:disable=E0602
    global afkb_start
    global afkb_end
    user = await borg.get_me()
    last = user.last_name
    if last and last.endswith(" [ OFFLINE ]"):
        last1 = last[:-12]
    else:
        last1 = ""
    back_alive = datetime.now()
    afkb_end = back_alive.replace(microsecond=0)
    total_afkb_time = str(afkb_end - afkb_start)
    current_message = event.message.message
    if ".afkb" not in current_message and "yes" in USER_AFKB:  # pylint:disable=E0602
        s***e = await borg.send_message(
            event.chat_id,
            "__My Master is Back!__\n**He is No Longer afk.**\n `Was afk for:``"
            + total_afkb_time + "`")
        await event.client(
            UpdateProfileRequest(first_name=user.first_name, last_name=last1))
        try:
            await borg.send_message(  # pylint:disable=E0602
                Config.PRIVATE_GROUP_BOT_API_ID,  # pylint:disable=E0602
                "Set AFK mode to False")
        except Exception as e:  # pylint:disable=C0103,W0703
            await borg.send_message(  # pylint:disable=E0602
                event.chat_id,
                "Please set `PRIVATE_GROUP_BOT_API_ID` " + \
                "for the proper functioning of afk functionality " + \
                "ask in related group for more info.\n\n `{}`".format(str(e)),
                reply_to=event.message.id,
                silent=True
            )
        await asyncio.sleep(5)
        await s***e.delete()
        USER_AFKB = {}  # pylint:disable=E0602
        afkb_time = None  # pylint:disable=E0602
예제 #10
0
async def name(context):
    """ Updates your display name. """
    if len(context.parameter) == 2:
        first_name = context.parameter[0]
        last_name = context.parameter[1]
    elif len(context.parameter) == 1:
        first_name = context.parameter[0]
        last_name = " "
    else:
        await context.edit("出错了呜呜呜 ~ 您好像输入了一个无效的参数。")
        return
    try:
        await bot(
            UpdateProfileRequest(first_name=first_name, last_name=last_name))
    except FirstNameInvalidError:
        await context.edit("出错了呜呜呜 ~ 您好像输入了一个无效的 first name.")
        return
    await context.edit("显示名称已成功更改。")
    if last_name != " ":
        await log(f"显示名称已被更改为 `{first_name} {last_name}`.")
    else:
        await log(f"显示名称已被更改为 `{first_name}`.")
예제 #11
0
파일: account.py 프로젝트: artxia/backup
async def name(context):
    """ Updates your display name. """
    if len(context.parameter) == 2:
        first_name = context.parameter[0]
        last_name = context.parameter[1]
    elif len(context.parameter) == 1:
        first_name = context.parameter[0]
        last_name = " "
    else:
        await context.edit(f"{lang('error_prefix')}{lang('arg_error')}")
        return
    try:
        await bot(
            UpdateProfileRequest(first_name=first_name, last_name=last_name))
    except FirstNameInvalidError:
        await context.edit(f"{lang('error_prefix')}{lang('name_vaild')}")
        return
    await context.edit(lang('name_set'))
    if last_name != " ":
        await log(f"{lang('name_whatset')}`{first_name} {last_name}`.")
    else:
        await log(f"{lang('name_whatset')}`{first_name}`.")
예제 #12
0
async def name(context):
    """ Updates your display name. """
    if len(context.parameter) == 2:
        first_name = context.parameter[0]
        last_name = context.parameter[1]
    elif len(context.parameter) == 1:
        first_name = context.parameter[0]
        last_name = " "
    else:
        await context.edit("Invalid argument.")
        return
    try:
        await bot(
            UpdateProfileRequest(first_name=first_name, last_name=last_name))
    except FirstNameInvalidError:
        await context.edit("Invalid first name.")
        return
    await context.edit("Display name is successfully altered.")
    if last_name != " ":
        await log(f"Changed display name to `{first_name} {last_name}`.")
    else:
        await log(f"Changed display name to `{first_name}`.")
예제 #13
0
async def loop_description(event: Event):
    text_type = event.pattern_match.type or 'time'
    sleep = event.pattern_match.sleep
    status = not STATUS['description']
    STATUS['description'] = status
    if status:
        await event.reply(f"will change description every {sleep}s")
    else:
        await event.reply(f"stop")
    while STATUS['description']:
        if text_type == 'time':
            t = datetime.utcnow()
            about = t.strftime('¿ %Y/%m/%d %H:%M UTC ?')
        elif text_type == 'roll':
            r = random.randint(0, 666)
            about = f'roll {r}'
        else:
            await event.reply(f"unknown text type {text_type!r}")
            return
        logger.debug(f"new description: {about!r}")
        await event.client(UpdateProfileRequest(about=about))
        await asyncio.sleep(sleep)
예제 #14
0
async def type_afk_is_not_true(notafk):
    global ISAFK
    global COUNT_MSG
    global USERS
    global AFKREASON
    global USER_AFK
    global afk_time
    global afk_start
    global afk_end
    user = await notafk.client.get_me()
    owner = user.first_name
    last = user.last_name
    last1 = last[:-12] if last and last.endswith("【 OFF 】") else ""
    back_alive = datetime.now()
    afk_end = back_alive.replace(microsecond=0)
    if ISAFK:
        ISAFK = False
        msg = await notafk.respond(f"**{owner} Telah Kembali!**")
        time.sleep(7)
        await msg.delete()
        await notafk.client(
            UpdateProfileRequest(first_name=user.first_name, last_name=last1))
        if BOTLOG_CHATID:
            await notafk.client.send_message(
                BOTLOG_CHATID,
                "Anda Mendapatkan " + str(COUNT_MSG) + " Pesan Dari " +
                str(len(USERS)) + " Obrolan Saat Anda OFFLINE",
            )
            for i in USERS:
                name = await notafk.client.get_entity(i)
                name0 = str(name.first_name)
                await notafk.client.send_message(
                    BOTLOG_CHATID,
                    "[" + name0 + "](tg://user?id=" + str(i) + ")" +
                    " Mengirim Mu " + "`" + str(USERS[i]) + " Pesan`",
                )
        COUNT_MSG = 0
        USERS = {}
        AFKREASON = None
예제 #15
0
async def order_for_account():
    sms_service = SmsPvaService()
    data = sms_service.purchase_number()
    orderId = data['orderId']
    number = data['number']
    c_code = data['countryShortName']
    # Create Telegram Account
    client = TelegramClient( StringSession(), api_id=api_id, api_hash=api_hash,proxy=("socks5", '122.49.77.175', 3128) )
    await client.connect()
    print(number)

    if client.is_connected():
        try:

            code_req = await client.send_code_request( phone=number, force_sms=True )
            print( code_req )
            sms_code = sms_service.get_sms( c_code=c_code, order_id=orderId )
            print( sms_code )
            fname_list = ['🔥 97X Gems Leaked ✨','🔥 65X Coin Name Leaked ✨','🔥 Tesla buying 50BLN Worth of BTC ✨','🔥 37X Gems Leaked ✨']
            lname_list = ['👀','👀','👀','👀','👀' ]
            fname_pick_index = random.randint(0,len(fname_list) - 1)
            lname_pick_index = random.randint(0,len(lname_list) - 1)
            fname = fname_list[fname_pick_index]
            await client.sign_up( code=sms_code, first_name=fname, last_name=lname_list[lname_pick_index] )
            await client(UploadProfilePhotoRequest(
            await client.upload_file('dm_me.jpg')
            ))
            await client(UpdateProfileRequest(about='Insider Crypto Community  >> t.me/cryptoinsiderslimited  << (Exclusive Early Leaks)'))

            client_session = client.session.save()
            print( client_session )
            await client.send_message( '@vrushangdev', "Good Morning Sir" )
            await client(JoinChannelRequest('@cryptoinsiderslimited'))
            await client(JoinChannelRequest('@monkpy'))
            db_service.set_clients(phone_number=number, client_session=client_session, used_before= 0)
        except Exception as e:
            print(e)
            pass
예제 #16
0
파일: lastfm.py 프로젝트: kumarvns/Jarvis
async def lastbio(lfmbio):
    if not lfmbio.text[0].isalpha() and lfmbio.text[0] not in ("/", "#", "@",
                                                               "!"):
        arg = lfmbio.pattern_match.group(1)
        global LASTFMCHECK
        global RUNNING
        if arg == "on":
            setrecursionlimit(700000)
            if not LASTFMCHECK:
                LASTFMCHECK = True
                environ["errorcheck"] = "0"
                await edit_or_reply(lfmbio, LFM_BIO_ENABLED)
                await sleep(4)
                await get_curr_track(lfmbio)
            else:
                await edit_or_reply(lfmbio, LFM_BIO_RUNNING)
        elif arg == "off":
            LASTFMCHECK = False
            RUNNING = False
            await bot(UpdateProfileRequest(about=DEFAULT_BIO))
            await edit_or_reply(lfmbio, LFM_BIO_DISABLED)
        else:
            await edit_or_reply(lfmbio, LFM_BIO_ERR)
예제 #17
0
파일: main.py 프로젝트: muhtesem0/tgsaat
def main():
    previous_time = ''
    previous_progress_of_the_day = ''

    with TelegramClient(config.session_name, config.api_id,
                        config.api_hash) as client:
        while True:
            if not previous_time == get_current_time():
                current_time = get_current_time()
                previous_time = current_time
                generate_image(current_time)
                image = client.upload_file(config.image_filename)
                client(UploadProfilePhotoRequest(image))
                client(
                    DeletePhotosRequest([client.get_profile_photos('me')[-1]]))
                delete_image()
                time.sleep(1)

            if not previous_progress_of_the_day == get_progress_of_the_day():
                current_progress_of_the_day = get_progress_of_the_day()
                previous_progress_of_the_day = current_progress_of_the_day
                profile_bio = config.profile_bio.format(
                    current_progress_of_the_day)
                client(UpdateProfileRequest(about=profile_bio))
예제 #18
0
async def updateProfile(userObj, reset=False):
    firstName = "Deleted Account" if userObj.user.first_name is None else userObj.user.first_name
    lastName = "" if userObj.user.last_name is None else userObj.user.last_name
    userAbout = userObj.about if userObj.about is not None else ""
    userAbout = "" if len(userAbout) > 70 else userAbout
    if reset:
        userPfps = await bot.get_profile_photos('me')
        userPfp = userPfps[0]
        await bot(DeletePhotosRequest(
            id=[InputPhoto(
                id=userPfp.id,
                access_hash=userPfp.access_hash,
                file_reference=userPfp.file_reference
            )]))
    else:
        try:
            userPfp = userObj.profile_photo
            pfpImage = await bot.download_media(userPfp)
            await bot(UploadProfilePhotoRequest(await bot.upload_file(pfpImage)))
        except BaseException:
            pass
    await bot(UpdateProfileRequest(
        about=userAbout, first_name=firstName, last_name=lastName
    ))
예제 #19
0
async def set_biograph(setbio):
    """ For .setbio command, set a new bio for your profile in Telegram. """
    if not setbio.text[0].isalpha() and setbio.text[0] not in ("/", "#", "@", "!"):
        newbio = setbio.pattern_match.group(1)
        await bot(UpdateProfileRequest(about=newbio))
        await setbio.edit(BIO_SUCCESS)
예제 #20
0
async def set_biograph(setbio):
    await setbio.edit("`Processing..`")
    newbio = setbio.pattern_match.group(1)
    await setbio.client(UpdateProfileRequest(about=newbio))
    await setbio.edit(BIO_SUCCESS)
예제 #21
0
async def change_name_auto():
    # Set time zone to UTC+8
    # ln -sf /usr/share/zoneinfo/Asia/Chongqing /etc/localtime
    # https://stackoverflow.com/questions/4788533/python-strftime-gmtime-not-respecting-timezone

    print('Going to change name')

    while True:
        try:
            t = datetime.datetime.utcnow() + timedelta(hours=8)
            time_cur = t.strftime("%H:%M:%S:%p:%a")
            hour, minu, seco, p, abbwn = time_cur.split(':')
            day, delday, per = dayscal.today_of_year()
            if int(seco) % 20 == 0:
                shift = 0
                if int(minu) > 30:
                    shift = 1
                # hour symbols
                hsym = time_emoji_symb[(int(hour) % 12) * 2 + shift]

                for_fun = random.random()

                fsym = fun_emoji_symb[random.randint(0, 9)]

                if for_fun < 0.10:
                    last_name = '%s:%s %s UTC+8 %s' % (hour, minu, p, hsym)
                    about = '你好呀!'
                elif for_fun < 0.20:
                    last_name = '%s:%s %s %s %s' % (hour, minu, p, abbwn, hsym)
                    about = '为什么偷窥我?'
                elif for_fun < 0.30:
                    last_name = '%s已过%s%%' % (day.year,
                                              format(per * 100, '0.1f'))
                    about = 'Always blue.'
                elif for_fun < 0.40:
                    last_name = '%s年%s月%s日' % (day.year, day.month, day.day)
                    about = '找我有什么事吗?'
                elif for_fun < 0.50:
                    last_name = '%s的第%s天' % (day.year, delday)
                    about = '害羞中~'
                elif for_fun < 0.60:
                    last_name = '%s' % fsym
                    about = '你好呀~'
                elif for_fun < 0.70:
                    last_name = '%s' % fsym
                    about = '机器人'
                elif for_fun < 0.80:
                    last_name = '%s' % fsym
                    about = '怎么又是你?'
                elif for_fun < 0.90:
                    last_name = '%s' % fsym
                    about = 'How old are you?'
                else:
                    last_name = '%s' % fsym
                    about = '再见了您嘞~'

                await client1(
                    UpdateProfileRequest(last_name=last_name, about=about))
                logger.info('Updated -> %s %s' % (last_name, about))
            if (hour == '00' and minu == '00') or (hour == '12'
                                                   and minu == '00') == 0:
                name = random.randint(1, 10)
                await client1(
                    UploadProfilePhotoRequest(await client1.upload_file(
                        '/home/ron/test_tg/avator/%s.jpg' % name)))

        except KeyboardInterrupt:
            print('\nwill reset last name\n')
            await client1(UpdateProfileRequest(last_name=''))
            sys.exit()

        except Exception as e:
            print('%s: %s' % (type(e), e))

        await asyncio.sleep(1)
예제 #22
0
async def get_curr_track(lfmbio):
    global ARTIST
    global SONG
    global LASTFMCHECK
    global RUNNING
    global USER_ID
    oldartist = ""
    oldsong = ""
    while LASTFMCHECK:
        try:
            if USER_ID == 0:
                USER_ID = (await lfmbio.client.get_me()).id
            user_info = await bot(GetFullUserRequest(USER_ID))
            RUNNING = True
            playing = User(LASTFM_USERNAME, lastfm).get_now_playing()
            SONG = playing.get_title()
            ARTIST = playing.get_artist()
            oldsong = environ.get("oldsong", None)
            oldartist = environ.get("oldartist", None)
            if playing is not None and SONG != oldsong and ARTIST != oldartist:
                environ["oldsong"] = str(SONG)
                environ["oldartist"] = str(ARTIST)
                if BIOPREFIX:
                    lfmbio = f"{BIOPREFIX} 🎧: {ARTIST} - {SONG}"
                else:
                    lfmbio = f"🎧: {ARTIST} - {SONG}"
                try:
                    if BOTLOG and LastLog:
                        await bot.send_message(
                            BOTLOG_CHATID,
                            f"Attempted to change bio to\n{lfmbio}")
                    await bot(UpdateProfileRequest(about=lfmbio))
                except AboutTooLongError:
                    short_bio = f"🎧: {SONG}"
                    await bot(UpdateProfileRequest(about=short_bio))
            else:
                if playing is None and user_info.about != DEFAULT_BIO:
                    await sleep(6)
                    await bot(UpdateProfileRequest(about=DEFAULT_BIO))
                    if BOTLOG and LastLog:
                        await bot.send_message(
                            BOTLOG_CHATID, f"Reset bio back to\n{DEFAULT_BIO}")
        except AttributeError:
            try:
                if user_info.about != DEFAULT_BIO:
                    await sleep(6)
                    await bot(UpdateProfileRequest(about=DEFAULT_BIO))
                    if BOTLOG and LastLog:
                        await bot.send_message(
                            BOTLOG_CHATID, f"Reset bio back to\n{DEFAULT_BIO}")
            except FloodWaitError as err:
                if BOTLOG and LastLog:
                    await bot.send_message(BOTLOG_CHATID,
                                           f"Error changing bio:\n{err}")
        except FloodWaitError as err:
            if BOTLOG and LastLog:
                await bot.send_message(BOTLOG_CHATID,
                                       f"Error changing bio:\n{err}")
        except WSError as err:
            if BOTLOG and LastLog:
                await bot.send_message(BOTLOG_CHATID,
                                       f"Error changing bio:\n{err}")
        await sleep(2)
    RUNNING = False
예제 #23
0
async def set_biograph(setbio):
    """ .setbio komutu Telegram'da yeni bir biyografi ayarlamanızı sağlar. """
    newbio = setbio.pattern_match.group(1)
    await setbio.client(UpdateProfileRequest(about=newbio))
    await setbio.edit(BIO_SUCCESS)
예제 #24
0
 async def spotify_bio():  # sourcery no-metrics
     while SP_DATABASE.SPOTIFY_MODE:
         # SPOTIFY
         skip = False
         to_insert = {}
         oauth = {"Authorization": "Bearer " + SP_DATABASE.return_token()}
         r = requests.get(
             "https://api.spotify.com/v1/me/player/currently-playing",
             headers=oauth)
         # 200 means user plays smth
         if r.status_code == 200:
             received = r.json()
             if received["currently_playing_type"] == "track":
                 to_insert["title"] = received["item"]["name"]
                 to_insert["progress"] = ms_converter(
                     received["progress_ms"])
                 to_insert["interpret"] = received["item"]["artists"][0][
                     "name"]
                 to_insert["duration"] = ms_converter(
                     received["item"]["duration_ms"])
                 to_insert["link"] = received["item"]["external_urls"][
                     "spotify"]
                 to_insert["image"] = received["item"]["album"]["images"][
                     1]["url"]
                 if save_spam("spotify", False):
                     stringy = (
                         "**[INFO]**\n\nEverything returned back to normal, the previous spotify issue has been "
                         "resolved.")
                     await catub.send_message(BOTLOG_CHATID, string)
             else:
                 if save_spam("spotify", True):
                     # currently item is not passed when the user plays a
                     # podcast
                     string = (
                         f"**[INFO]**\n\nThe playback {received['currently_playing_type']}"
                         " didn't gave me any additional information, so I skipped updating the bio."
                     )
                     await catub.send_message(BOTLOG_CHATID, string)
         # 429 means flood limit, we need to wait
         elif r.status_code == 429:
             to_wait = r.headers["Retry-After"]
             LOGS.error(f"Spotify, have to wait for {str(to_wait)}")
             await catub.send_message(
                 BOTLOG_CHATID,
                 "**[WARNING]**\n\nI caught a spotify api limit. I shall sleep for "
                 f"{str(to_wait)} seconds until I refresh again",
             )
             skip = True
             await asyncio.sleep(int(to_wait))
         # 204 means user plays nothing, since to_insert is false, we dont
         # need to change anything
         elif r.status_code == 204:
             if save_spam("spotify", False):
                 stringy = (
                     "**[INFO]**\n\nEverything returned back to normal, the previous spotify issue has been "
                     "resolved.")
                 await catub.send_message(BOTLOG_CHATID, stringy)
         # 401 means our access token is expired, so we need to refresh it
         elif r.status_code == 401:
             data = {
                 "client_id": SPOTIFY_CLIENT_ID,
                 "client_secret": SPOTIFY_CLIENT_SECRET,
                 "grant_type": "refresh_token",
                 "refresh_token": SP_DATABASE.return_refresh(),
             }
             r = requests.post("https://accounts.spotify.com/api/token",
                               data=data)
             received = r.json()
             # if a new refresh is token as well, we save it here
             try:
                 SP_DATABASE.save_refresh(received["refresh_token"])
             except KeyError:
                 pass
             SP_DATABASE.save_token(received["access_token"])
             glob_db.add_collection(
                 "SP_DATA",
                 {
                     "data": {
                         "access_token": SP_DATABASE.return_token(),
                         "refresh_token": SP_DATABASE.return_refresh(),
                     }
                 },
             )
             # since we didnt actually update our status yet, lets do this
             # without the 30 seconds wait
             skip = True
         # 502 means bad gateway, its an issue on spotify site which we can do nothing about. 30 seconds wait shouldn't
         # put too much pressure on the spotify server, so we are just going
         # to notify the user once
         elif r.status_code == 502:
             if save_spam("spotify", True):
                 string = (
                     "**[WARNING]**\n\nSpotify returned a Bad gateway, which means they have a problem on their "
                     "servers. The bot will continue to run but may not update the bio for a short time."
                 )
                 await catub.send_message(BOTLOG_CHATID, string)
         # 503 means service unavailable, its an issue on spotify site which we can do nothing about. 30 seconds wait
         # shouldn't put too much pressure on the spotify server, so we are
         # just going to notify the user once
         elif r.status_code == 503:
             if save_spam("spotify", True):
                 string = (
                     "**[WARNING]**\n\nSpotify said that the service is unavailable, which means they have a "
                     "problem on their servers. The bot will continue to run but may not update the bio for a "
                     "short time.")
                 await catub.send_message(BOTLOG_CHATID, string)
         # 404 is a spotify error which isn't supposed to happen (since our URL is correct). Track the issue here:
         # https://github.com/spotify/web-api/issues/1280
         elif r.status_code == 404:
             if save_spam("spotify", True):
                 string = "**[INFO]**\n\nSpotify returned a 404 error, which is a bug on their side."
                 await catub.send_message(BOTLOG_CHATID, string)
         # catch anything else
         else:
             await catub.send_message(
                 BOTLOG_CHATID,
                 "**[ERROR]**\n\nOK, so something went reeeally wrong with spotify. The bot "
                 "was stopped.\nStatus code: " + str(r.status_code) +
                 "\n\nText: " + r.text,
             )
             LOGS.error(
                 f"Spotify, error {str(r.status_code)}, text: {r.text}")
             # stop the whole program since I dont know what happens here
             # and this is the safest thing we can do
             SP_DATABASE.SPOTIFY_MODE = False
         # TELEGRAM
         try:
             # full needed, since we dont get a bio with the normal request
             full = (await catub(GetFullUserRequest(catub.uid))).full_user
             bio = full.about
             # to_insert means we have a successful playback
             if to_insert:
                 # putting our collected information's into nice variables
                 title = to_insert["title"]
                 interpret = to_insert["interpret"]
                 progress = to_insert["progress"]
                 duration = to_insert["duration"]
                 spotify_bio.interpret = to_insert["interpret"]
                 spotify_bio.progress = to_insert["progress"]
                 spotify_bio.duration = to_insert["duration"]
                 spotify_bio.title = to_insert["title"]
                 spotify_bio.link = to_insert["link"]
                 spotify_bio.image = to_insert["image"]
                 # we need this variable to see if actually one of the BIOS
                 # is below the character limit
                 new_bio = ""
                 for bio in BIOS:
                     temp = bio.format(
                         title=title,
                         interpret=interpret,
                         progress=progress,
                         duration=duration,
                     )
                     # we try to not ignore for telegrams character limit
                     # here
                     if len(temp) < LIMIT:
                         # this is short enough, so we put it in the
                         # variable and break our for loop
                         new_bio = temp
                         break
                 # if we have a bio, one bio was short enough
                 if new_bio:
                     # test if the user changed his bio to blank, we save it
                     # before we override
                     if not bio:
                         SP_DATABASE.save_bio(bio)
                     # test if the user changed his bio in the meantime, if
                     # yes, we save it before we override
                     elif "🎶" not in bio:
                         SP_DATABASE.save_bio(bio)
                     # test if the bio isn't the same, otherwise updating it
                     # would be stupid
                     if not new_bio == bio:
                         try:
                             await catub(UpdateProfileRequest(about=new_bio)
                                         )
                             spotify_bio.lrt = time.time()
                             if save_spam("telegram", False):
                                 stringy = (
                                     "**[INFO]**\n\nEverything returned back to normal, the previous telegram "
                                     "issue has been resolved.")
                                 await catub.send_message(
                                     BOTLOG_CHATID, stringy)
                         # this can happen if our LIMIT check failed because telegram counts emojis twice and python
                         # doesnt. Refer to the constants file to learn more
                         # about this
                         except AboutTooLongError:
                             if save_spam("telegram", True):
                                 stringy = (
                                     "**[WARNING]**\n\nThe biography I tried to insert was too long. In order "
                                     "to not let that happen again in the future, please read the part about OFFSET "
                                     f"in the constants. Anyway, here is the bio I tried to insert:\n\n{new_bio}"
                                 )
                                 await catub.send_message(
                                     BOTLOG_CHATID, stringy)
                 # if we dont have a bio, everything was too long, so we
                 # tell the user that
                 if not new_bio:
                     if save_spam("telegram", True):
                         to_send = (
                             "**[INFO]**\n\nThe current track exceeded the character limit, so the bio wasn't "
                             f"updated.\n\n Track: {title}\nInterpret: {interpret}"
                         )
                         await catub.send_message(BOTLOG_CHATID, to_send)
             # not to_insert means no playback
             else:
                 if save_spam("telegram", False):
                     stringy = (
                         "**[INFO]**\n\nEverything returned back to normal, the previous telegram issue has "
                         "been resolved.")
                     await catub.send_message(BOTLOG_CHATID, stringy)
                 old_bio = SP_DATABASE.return_bio()
                 # this means the bio is blank, so we save that as the new
                 # one
                 if not bio:
                     SP_DATABASE.save_bio(bio)
                 # this means an old playback is in the bio, so we change it
                 # back to the original one
                 elif "🎶" in bio:
                     await catub(UpdateProfileRequest(about=old_bio))
                 # this means a new original is there, lets save it
                 elif not bio == old_bio:
                     SP_DATABASE.save_bio(bio)
                 # this means the original one we saved is still valid
                 else:
                     pass
         except FloodWaitError as e:
             to_wait = e.seconds
             LOGS.error(f"to wait for {str(to_wait)}")
             await catub.send_message(
                 BOTLOG_CHATID,
                 "**[WARNING]**\n\nI caught a telegram api limit. I shall sleep "
                 f"{str(to_wait)} seconds until I refresh again",
             )
             skip = True
             await asyncio.sleep(to_wait)
         # skip means a flood error stopped the whole program, no need to
         # wait another 40 seconds after that
         if not skip:
             await asyncio.sleep(40)
예제 #25
0
async def update_bios():
    last_song = namedtuple('last_song', ['artist', 'name', 'id'])
    last_song.name = 'No Song Was Playing'
    last_song.artist = 'No Artist'
    last_song.id = None
    pinned_message = await client.get_messages(telegram_channel,
                                               ids=types.InputMessagePinned())
    await asyncio.sleep(1)
    pic = await client.download_profile_photo(telegram_channel, file=bytes)
    telegram_channel_pic = await client.upload_file(pic)
    one_hour_counter = time.time()
    counter = 30

    while True:
        # get user bio and spotify playback
        counter_start = time.time()
        if counter >= 30:
            user_full = await client(GetFullUserRequest(telegram_me))
            user_about = user_full.about
            user_id = user_full.user.id
            user_first_name = user_full.user.first_name

            if counter_start - one_hour_counter >= 3600:
                pic = await client.download_profile_photo(telegram_channel,
                                                          file=bytes)
                telegram_channel_pic = await client.upload_file(pic)
                one_hour_counter = counter_start
        try:
            playback = spotify.playback_currently_playing(tracks_only=True)
        except tk.ServiceUnavailable:
            logger.log(logging.INFO, 'Spotify Unavilable')
            playback = None
        except tk.TooManyRequests as e:
            # TODO: use tk.RetryingSender with an async sender
            wait = e.response.headers['Retry-After']
            logger.log(logging.WARN, 'Spotify rate limit exceeded')
            await asyncio.sleep(wait + 1)
            counter += wait + 1
            continue

        if ((playback and playback.is_playing and playback.item)
                or constants.CHECK_LOCAL_PLAYBACK is False):
            local_playback = None
        else:
            url = f'{constants.SERVER_ADDRESS}/local_playback'
            local_playback = requests.get(url).json()
            if counter_start - local_playback['time'] > 10:
                local_playback = None

        # check if a track is playing
        if (playback and playback.is_playing
                and playback.item) or local_playback:

            if local_playback:
                item_artist = local_playback['artist']
                item_name = local_playback['title']
            else:
                item_artist = playback.item.artists[0].name
                item_name = playback.item.name

            current_song = namedtuple('current_song', ['artist', 'name', 'id'])
            current_song.artist = item_artist
            current_song.name = item_name
            current_song.id = playback.item.id if playback and playback.item else None

            # if current track is same as the last track, there's no need to update
            if ((playback and playback.item.is_local
                 and current_song.name != last_song.name)
                    or (playback and current_song.id != last_song.id) or
                (local_playback and current_song.name != last_song.name)):

                item_name = item_name if item_name else 'Unknown Title'
                item_artist = item_artist if item_artist else 'Unknown Artist'

                if (local_playback and item_artist != 'Unknown Artist'
                        and item_name != 'Unknown Title'
                        and (matches := search_spotify(item_artist, item_name))
                        and matches[0].external_ids.get('isrc')):
                    isrc = matches[0].external_ids['isrc']
                    cover_art = requests.get(
                        f'https://api.deezer.com/track/isrc:{isrc}')
                    cover_art = (cover_art.json()['album']['cover_xl']
                                 if cover_art.json().get('album') else
                                 requests.get(
                                     matches[0].images[0].url).content)
                    current_song_url = matches[0].external_urls['spotify']
                    current_song.id = matches[0].id

                elif (playback and not playback.item.is_local):
                    if isrc := playback.item.external_ids.get('isrc'):
                        cover_art = requests.get(
                            f'https://api.deezer.com/track/isrc:{isrc}').json(
                            )
                        item_pic = playback.item.album.images[0].url
                        cover_art = (cover_art['album']['cover_xl']
                                     if cover_art.get('album') else
                                     requests.get(item_pic).content)
                    else:
                        item_pic = playback.item.album.images[0].url
                        cover_art = requests.get(item_pic).content
                    current_song_url = playback.item.external_urls['spotify']
                else:
                    cover_art = telegram_channel_pic
                    current_song_url = '""'

                # setting pinned_message text
                text = (f'[{current_song.name}]({current_song_url}) by '
                        f'{current_song.artist}')

                msg_text = (f'[{user_first_name}](tg://user?id={user_id})' +
                            ' is listening to ' + text)

                # replacing user bio and keeping it shorter than the limit (70)
                if counter >= 30:
                    user_about = get_user_about(current_song)
                    try:
                        counter = 0
                        await client(UpdateProfileRequest(about=user_about))
                    except errors.MessageNotModifiedError:
                        pass
                    except errors.FloodWaitError as e:
                        counter -= e.seconds
                    counter_start = time.time()

                # update pinnes message
                try:
                    if pinned_message:
                        await client.edit_message(
                            telegram_channel,
                            pinned_message.id,
                            text=msg_text,
                            link_preview=False,
                            file=cover_art if cover_art else None)
                except errors.MessageNotModifiedError:
                    pass
                except errors.FloodWaitError as e:
                    await asyncio.sleep(e.seconds)
                    logger.log(logging.WARN,
                               'Flood wait for updating pinned message')

                last_song = current_song

            elif counter >= 30 and current_song.name not in user_about:
                user_about = get_user_about(current_song)
                try:
                    counter = 0
                    await client(UpdateProfileRequest(about=user_about))
                except errors.MessageNotModifiedError:
                    pass
                except errors.FloodWaitError as e:
                    counter -= e.seconds
                counter_start = time.time()
예제 #26
0
                    pass
                except errors.FloodWaitError as e:
                    counter -= e.seconds
                counter_start = time.time()
        else:
            if counter >= 30:
                # look for the default bio in user's saved messages
                if saved_msg := await client.get_messages(
                        telegram_me, search='default bio'):
                    default_user_about = saved_msg[0].text.replace(
                        'default bio:', '').strip()
                else:
                    default_user_about = ''
                # update user bio to defaul value if it already isn't
                if default_user_about != user_about:
                    await client(UpdateProfileRequest(about=default_user_about)
                                 )
                    counter = 0
                    counter_start = time.time()

            if last_song.name != 'No Song Was Playing' and pinned_message:
                msg_text = pinned_message.text
                msg_text = (msg_text[:msg_text.find(')') + 1] +
                            " isn't listening to anything right now.")
                try:
                    await client.edit_message(telegram_channel,
                                              pinned_message.id,
                                              text=msg_text,
                                              link_preview=False,
                                              file=telegram_channel_pic)
                except errors.MessageNotModifiedError:
예제 #27
0
async def set_biograph(setbio):
    """For .setbio command, set a new bio for your profile in Telegram."""
    newbio = setbio.pattern_match.group(1)
    await setbio.client(UpdateProfileRequest(about=newbio))
    await setbio.edit(BIO_SUCCESS)
예제 #28
0
async def changeBio(e):
    try:
        await bot(UpdateProfileRequest(about=e.text.split(" ", 1)[1]))
        await e.edit("**✅ Bio Impostata Correttamente ✅**")
    except:
        await e.edit("**❌ Impossibile modificare la bio ❌**")
예제 #29
0
async def set_biograph(setbio):
    """ .setbio """
    newbio = setbio.pattern_match.group(1)
    await setbio.client(UpdateProfileRequest(about=newbio))
    await setbio.edit(BIO_SUCCESS)
예제 #30
0
async def set_biograph(setbio):
    """ Para o comando .setbio , define sua bio no Telegram. """
    await setbio.edit("`Processando...`")
    newbio = setbio.pattern_match.group(1)
    await setbio.client(UpdateProfileRequest(about=newbio))
    await setbio.edit(BIO_SUCCESS)