Example #1
0
async def hash(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        hashtxt_ = e.pattern_match.group(1)
        hashtxt = open("hashdis.txt", "w+")
        hashtxt.write(hashtxt_)
        hashtxt.close()
        md5 = subprocess.run(["md5sum", "hashdis.txt"], stdout=subprocess.PIPE)
        md5 = md5.stdout.decode()
        sha1 = subprocess.run(["sha1sum", "hashdis.txt"],
                              stdout=subprocess.PIPE)
        sha1 = sha1.stdout.decode()
        sha256 = subprocess.run(["sha256sum", "hashdis.txt"],
                                stdout=subprocess.PIPE)
        sha256 = sha256.stdout.decode()
        sha512 = subprocess.run(["sha512sum", "hashdis.txt"],
                                stdout=subprocess.PIPE)
        subprocess.run(["rm", "hashdis.txt"], stdout=subprocess.PIPE)
        sha512 = sha512.stdout.decode()
        ans = ("Text: `" + hashtxt_ + "`\nMD5: `" + md5 + "`SHA1: `" + sha1 +
               "`SHA256: `" + sha256 + "`SHA512: `" + sha512[:-1] + "`")
        if len(ans) > 4096:
            f = open("hashes.txt", "w+")
            f.write(ans)
            f.close()
            await bot.send_file(
                e.chat_id,
                "hashes.txt",
                reply_to=e.id,
                caption="`It's too big, in a text file and hastebin instead. `"
                + hastebin.post(ans[1:-1]),
            )
            subprocess.run(["rm", "hashes.txt"], stdout=subprocess.PIPE)
        else:
            await e.reply(ans)
Example #2
0
async def hash(e):
    hashtxt_ = e.pattern_match.group(1)
    hashtxt = open('hashdis.txt', 'w+')
    hashtxt.write(hashtxt_)
    hashtxt.close()
    md5 = subprocess.run(['md5sum', 'hashdis.txt'], stdout=subprocess.PIPE)
    md5 = md5.stdout.decode()
    sha1 = subprocess.run(['sha1sum', 'hashdis.txt'], stdout=subprocess.PIPE)
    sha1 = sha1.stdout.decode()
    sha256 = subprocess.run(['sha256sum', 'hashdis.txt'],
                            stdout=subprocess.PIPE)
    sha256 = sha256.stdout.decode()
    sha512 = subprocess.run(['sha512sum', 'hashdis.txt'],
                            stdout=subprocess.PIPE)
    subprocess.run(['rm', 'hashdis.txt'], stdout=subprocess.PIPE)
    sha512 = sha512.stdout.decode()
    ans = 'Text: `' + hashtxt_ + '`\nMD5: `' + md5 + '`SHA1: `' + sha1 + '`SHA256: `' + sha256 + '`SHA512: `' + sha512[:
                                                                                                                       -1] + '`'
    if len(ans) > 4096:
        f = open('hashes.txt', 'w+')
        f.write(ans)
        f.close()
        await bot.send_file(
            e.chat_id,
            'hashes.txt',
            reply_to=e.id,
            caption="`It's too big, in a text file and hastebin instead. `" +
            hastebin.post(ans[1:-1]))
        subprocess.run(['rm', 'hashes.txt'], stdout=subprocess.PIPE)
    else:
        await e.reply(ans)
Example #3
0
async def haste_paste(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        message = e.text
        await e.edit("`Pasting text . . .`")
        text = str(message[7:])
        await e.edit("`Paste successful! Check it here: `" +
                     hastebin.post(text))
async def evaluate(e):
    evaluation = eval(e.text[6:])
    if inspect.isawaitable(evaluation):
        evaluation = await evaluation
    if evaluation:
        if len(evaluation) > 4096:
            f = open('sender.txt', 'w+')
            f.write(evaluation)
            f.close()
            await bot.send_file(
                e.chat_id,
                'sender.txt',
                reply_to=e.id,
                caption="`It's too big to send as text, sent to hastebin: `" +
                hastebin.post(evaluation[1:-1]))
            subprocess.run(['rm', 'sender.txt'], stdout=subprocess.PIPE)
        await e.edit("**Query: **\n`" + e.text[6:] + '`\n**Result: **\n`' +
                     str(evaluation) + '`')
    else:
        await e.edit("**Query: **\n`" + e.text[6:] +
                     '`\n**Result: **\n`No Result Returned/False`')
    if LOGGER:
        await bot.send_message(
            LOGGER_GROUP,
            "Eval query " + e.text[6:] + " was executed successfully")
async def run(e):
    code = e.raw_text[5:]
    exec(f'async def __ex(e): ' + ''.join(f'\n {l}' for l in code.split('\n')))
    result = await locals()['__ex'](e)
    if result:
        if len(result) > 4096:
            f = open('sender.txt', 'w+')
            f.write(result)
            f.close()
            await bot.send_file(
                e.chat_id,
                'sender.txt',
                reply_to=e.id,
                caption="`It's too big to send as text, sent to hastebin: `" +
                hastebin.post(result[1:-1]))
            subprocess.run(['rm', 'sender.txt'], stdout=subprocess.PIPE)
        await e.edit("**Query: **\n`" + e.text[5:] + '`\n**Result: **\n`' +
                     str(result) + '`')
    else:
        await e.edit("**Query: **\n`" + e.text[5:] + '`\n**Result: **\n`' +
                     'No Result Returned/False' + '`')
    if LOGGER:
        await bot.send_message(
            LOGGER_GROUP,
            "Exec query " + e.text[5:] + " was executed successfully")
Example #6
0
async def haste_paste(e):
    if not e.text[0].isalpha() and e.text[0] != "!" and e.text[
            0] != "/" and e.text[0] != "#" and e.text[0] != "@":
        message = e.text
        await e.edit('`Pasting text . . .`')
        text = str(message[7:])
        await e.edit('`Paste successful! Check it here: `' +
                     hastebin.post(text))
Example #7
0
async def bot_reply(msg,
                    client,
                    signal,
                    code_output="",
                    compiler_output="",
                    language=""):
    """Makes the bot reply depending on the signal."""

    try:
        if signal == 0:  # There was no code detected on the message
            await client.send_message(
                msg.channel, "I'm sorry, but I'm not seeing any code to run.")
        elif signal == 1:  # There was only a mention of the bot
            await send_instructions(msg, client)
        elif signal == 2:  # detect_language() couldn't detect the language
            await client.send_message(
                msg.channel,
                "I'm sorry, but you didn't specify the language of the code or it isn't supported yet."
            )
        elif signal == 3:  # The compiler ran into issues
            await client.send_message(
                msg.channel,
                "I've encountered the following error when compiling your %s code. \n```\n%s```"
                % (language, compiler_output))
        elif signal == 4:  # The process timeouted
            await client.send_message(
                msg.channel,
                "I'm sorry, but your request took too long. Here are the last 5 lines from the output.\n```\n%s```"
                % code_output)
        elif signal == 5:  # There were errors when running the code
            await client.send_message(
                msg.channel,
                "I've encountered the following error when running your %s code. \n```\n%s```"
                % (language, code_output))
        elif signal == 6:  # Everything went well
            await client.send_message(
                msg.channel,
                "Here's the output of your %s code. \n```\n%s```" %
                (language, code_output))
    except discord.errors.HTTPException:  # Unless the message was +2000 characters
        try:
            await client.send_message(
                msg.channel,
                "I'm sorry, but the output is too long for Discord. You can check the output of your %s code here. %s"
                % (language, hastebin.post(code_output)))
        except KeyError:  # Not even hastebin wants the output
            await client.send_message(
                msg.channel,
                "I'm sorry, but the output is too long for Discord. Hell, it's even too long for hastebin. Though luck, I guess. *¯\_(ツ)_/¯*"
            )
Example #8
0
    async def hastebin(self, ctx, text=None):
        if not text:
            await ctx.send('Usage: **;hastebin {text}**')
            return

        t = ctx.message.content.split(' ')
        del t[0]
        text = ' '.join(t)
        try:
            a = hastebin.post(text)
        except Exception as e:
            return await ctx.send(
                "Oh, no looks hastebin server is dead please try this command later ehen server will be fixed"
            )
        await ctx.send(embed=discord.Embed(title=f'Done you post here -> {a}'))
Example #9
0
async def paste(pstl):
    if not pstl.text[0].isalpha() and pstl.text[0] not in ("/", "#", "@", "!"):
        dogbin_final_url = ""

        textx = await pstl.get_reply_message()
        message = pstl.text
        await pstl.edit("`Pasting text . . .`")
        if message[7:]:
            message = str(message[7:])
        elif textx:
            message = str(textx.message)

        # Dogbin
        r = requests.post(DOGBIN_URL + "documents",
                          data=message.encode('utf-8'))

        # Hastebin
        try:
            hastebin_final_url = hastebin.post(message)
        except Exception:
            hastebin_final_url = "`Failed to reach hastebin`"

        if r.status_code == 200:
            response = r.json()
            key = response['key']
            dogbin_final_url = DOGBIN_URL + key

            if response['isUrl']:
                reply_text = ("`Pasted successfully!`\n\n"
                              f"`Shortened URL:` {dogbin_final_url}\n\n`"
                              "Original(non-shortened) URLs`\n"
                              f"`Dogbin URL`: {DOGBIN_URL}v/{key}\n`"
                              f"Hastebin URL`: {hastebin_final_url}")
            else:
                reply_text = ("`Pasted successfully!`\n\n"
                              f"`Dogbin URL`: {dogbin_final_url}\n`"
                              f"Hastebin URL`: {hastebin_final_url}")
        else:
            reply_text = ("`Pasted successfully!`\n\n"
                          "`Dogbin URL`: `Failed to reach dogbin`"
                          f"\n`Hastebin URL`: {hastebin_final_url}")

        await pstl.edit(reply_text)
        if LOGGER:
            await bot.send_message(
                LOGGER_GROUP,
                "Paste query `" + message + "` was executed successfully",
            )
Example #10
0
 async def code(self, ctx, *, something=None):
     owner = [343395225571426304, 402829897514352641]
     if ctx.author.id in owner:
         try:
             if something is None:
                 await ctx.send('What would you like me to say? :thinking:')
             else:
                 await ctx.send(('```py\n' + str(inspect.getsource(self.bot.get_command(something).callback)) + '```'))
         except Exception as e:
             try:
                 await ctx.send(hastebin.post(str(inspect.getsource(self.bot.get_command(something).callback))))
             except Exception as e:
                 await ctx.send('Given function do not exist')
                 print(e)
     else:
         await ctx.send('I only listen to my owner')
     print('code')
async def terminal_runner(e):
    message = e.text
    command = str(message)
    list_x = command.split(' ')
    result = subprocess.run(list_x[1:], stdout=subprocess.PIPE)
    result = str(result.stdout.decode())
    if len(result) > 4096:
        f = open('sender.txt', 'w+')
        f.write(result)
        f.close()
        await bot.send_file(
            e.chat_id,
            'sender.txt',
            reply_to=e.id,
            caption="`It's too big to send as text, sent to hastebin: `" +
            hastebin.post(result[1:-1]))
        subprocess.run(['rm', 'sender.txt'], stdout=subprocess.PIPE)
    await e.edit("**Query: **\n`" + str(command[6:]) + '`\n**Output: **\n`' +
                 result + '`')
    if LOGGER:
        await bot.send_message(
            LOGGER_GROUP, "Terminal Command " + str(list_x[1:]) +
            " was executed sucessfully")
Example #12
0
def hbp(body: str) -> str:
    return post(body.encode("utf-8"))
Example #13
0
async def on_message(message):
    prefix = config['prefix']
    if message.author == client.user:
        return

    if message.content.startswith(prefix + 'ping'):
        await client.send_message(message.channel, "Pong")

    if message.content.startswith(prefix + 'CreateATC'):
        if len(message.content.split(" ")) != 3:
            await client.send_message(message.channel,
                                      "Invalid number of arguments")
        else:
            site = message.content.split(" ")[1]
            variant = message.content.split(" ")[2]
            atclink = "{}/cart/{}:1".format(site, variant)
            await client.send_message(message.channel, atclink)

    if message.content.startswith(prefix + 'Choose'):
        if len(message.content.split(" ")) != 2:
            await client.send_message(message.channel,
                                      "Invalid Number Of Arguments")
        else:
            options = message.content.split(" ")[1]
            opl = []
            optionsl = options.split(",")
            for op in optionsl:
                opl.append(op)

            opnum = randint(0, len(opl) - 1)
            option = opl[opnum]
            await client.send_message(message.channel,
                                      "I Choose {}".format(option))

    if message.content.startswith(prefix + 'ATC'):
        try:
            if len(message.content.split(" ")) != 2:
                await client.send_message(message.channel,
                                          "Invalid Number Of Arguments")
            else:
                produrl = message.content.split(" ")[1]
                s = requests.session()
                prodobjr = s.get(produrl)
                prodobj = prodobjr.text.split("var meta = ")[1]
                prodobj = prodobj.split(";")[0]
                prodobj = json.loads(prodobj)
                soup = bs(prodobjr.text, "html.parser")
                actionheaders = {
                    'Authorization': 'Bot {}'.format(token),
                    'User-Agent': 'XO Discord Bot (https://xobots.io, v0.1)',
                    'Content-Type': 'application/json'
                }
                actionlink = "https://discordapp.com/api/channels/{}/webhooks".format(
                    message.channel.id)

                actiondata = {
                    "name": "CopSiteList",
                }
                createwh = s.post(actionlink,
                                  headers=actionheaders,
                                  data=json.dumps(actiondata))
                webhookObject = json.loads(createwh.text)
                whid = webhookObject['id']
                whtoken = webhookObject['token']
                webhookurl = "https://discordapp.com/api/webhooks/{}/{}".format(
                    whid, whtoken)
                colornum = randint(0, len(colorArray) - 1)
                color = colorArray[colornum]
                embed = Webhook(webhookurl, color=color)
                embed.set_author(name='XO Discord Bot | BY XO')
                embed.set_footer(
                    text=
                    'Discord Bot By XO Dev | Twitter @ehxohd | Discord XO#0001',
                    ts=True)
                prodsiteLink = produrl.split("/")[2]
                prodsiteLink = "https://{}".format(prodsiteLink)
                for pid in prodobj['product']['variants']:
                    embed.add_field(name=str(pid['public_title']),
                                    value="{}/cart/{}:1".format(
                                        prodsiteLink, pid['id']))

                embed.post()
                actionurl = "https://discordapp.com/api/webhooks/{}".format(
                    whid)
                s.delete(actionurl, headers=actionheaders)
        except:
            await client.send_message(message.channel,
                                      "Error Executing Scraper")

    if message.content.startswith(prefix + "Creator"):
        s = requests.session()
        colorNum = randint(0, len(colorArray) - 1)
        color = colorArray[colorNum]

        actionheaders = {
            'Authorization': 'Bot {}'.format(token),
            'User-Agent': 'XO Discord Bot (https://xobots.io, v0.1)',
            'Content-Type': 'application/json'
        }
        actionlink = "https://discordapp.com/api/channels/{}/webhooks".format(
            message.channel.id)

        actiondata = {
            "name": "CopSiteList",
        }
        createwh = s.post(actionlink,
                          headers=actionheaders,
                          data=json.dumps(actiondata))
        webhookObject = json.loads(createwh.text)
        whid = webhookObject['id']
        whtoken = webhookObject['token']
        webhookurl = "https://discordapp.com/api/webhooks/{}/{}".format(
            whid, whtoken)
        embed = Webhook(webhookurl, color=color)
        embed.set_author(name='OX Discord Bot')
        embed.set_desc(
            'This Is A Discord Bot Focused Around Sneakers Made By XO')
        embed.add_field(name="XO's Github URL",
                        value='https://github.com/TCWTEAM')
        embed.add_field(name="This Projects Github Repo",
                        value='https://github.com/TCWTEAM/OX-Discord-Bot')
        embed.set_thumbnail(
            'https://i.gyazo.com/b6c555781abae4b1c6719242589c7f50.png')
        embed.add_field(name="XO's Twitter",
                        value='https://twitter.com/ehxohd')
        embed.add_field(name="Want To Buy Me Lunch?",
                        value="https://www.paypal.me/EHXOH")
        embed.set_footer(text='XO Discord Bot | 2018', ts=True)
        embed.post()

        actionurl = "https://discordapp.com/api/webhooks/{}".format(whid)
        s.delete(actionurl, headers=actionheaders)

    if message.content.startswith(prefix + "IsShopify"):
        if len(message.content.split(" ")) != 2:
            await client.send_message(message.channel,
                                      "Invalid Number Of Arguemts")
        elif "http" not in message.content.split(" ")[1]:
            await client.send_message(message.channel, "Invalid Url")
        else:
            try:

                s = requests.session()
                headers = {
                    'User-Agent':
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
                }
                sitesource = s.get(message.content.split(" ")[1],
                                   headers=headers,
                                   timeout=15)
                if "Shopify" not in sitesource.text:
                    await client.send_message(
                        message.channel, "{} Is Not Shopify".format(
                            message.content.split(" ")[1]))
                else:
                    await client.send_message(
                        message.channel, "{} IS PROBABLY SHOPIFY".format(
                            message.content.split(" ")[1]))
            except:
                await client.send_message(
                    message.channel,
                    "Error Checking Site, Probably Rejected The Request")

    if message.content.startswith(prefix + "getproducts"):
        if len(message.content.split(" ")) < 2:
            await client.send_message(message.author,
                                      "Invalid Number Of Arguments")
        elif "http" not in message.content.split(" ")[1]:
            await client.send_message(message.author,
                                      "The URL You Gave Isnt Valid")
        else:
            url = message.content.split(" ")[1]
            s = requests.session()
            pagesource = s.get(url, headers=globalHeaders, timeout=20)
            if "shopify" not in pagesource.text.lower():
                await client.send_message(
                    message.author,
                    "The Site Requested Doesnt Seem To Be Shopify")
            else:
                testUrlr = s.get(url + "products.json",
                                 headers=globalHeaders,
                                 timeout=30)

            testUrlInfo = testUrlr.text
            productObject = json.loads(testUrlInfo)
            savefilenum = str(randint(111, 333))
            fnamee = "{}_{}.txt".format(
                url.split("://")[1].split(".")[0], savefilenum)
            f = open(fnamee, "w+")
            f.close()
            f = open(fnamee, "a+")
            f.write("SCRAPED BY XOS DISCORD BOT\n")
            f.write(
                "Twitter: @ehxohd | Discord: XO#0001 | Paypal: https://paypal.me/ehxoh\n"
            )
            f.write("=========================================\n")
            f.write("Info: \nSite Url:{}\nProduct Object URL:{}\n".format(
                url, url + "products.json"))
            f.write("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n")
            sitebaseurl = url.split("/")[2]
            for product in productObject['products']:
                f.write("=====================\n")
                name = product['title']
                f.write("Product Name: {}\n".format(name))
                f.write("Sizes And ATCS:\n")
                for variant in product['variants']:
                    f.write("----------------\n")
                    variantid = variant['id']
                    varname = variant['title'].replace("\/", "")
                    atclink = "{}/cart/{}:1".format(sitebaseurl, variantid)
                    f.write("VariantID: {}\n".format(variantid))
                    f.write("Size/Style: {}\n".format(varname))
                    f.write("ATC Link: {}\n".format(atclink))
                    f.write("----------------\n")
                f.write("=====================\n")

            f.write("END OF FILE\n")
            f.close()
            fc = open(fnamee, "r")
            fcc = fc.read()
            fc.close()

            textURL = hastebin.post(fcc)
            await client.send_message(
                message.author,
                "I Finished Scraping Your Sites. Heres What I Got\n{}".format(
                    textURL))
            os.remove(fnamee)

    if message.content.startswith(prefix + "help"):
        helpf = open("helpMessage.xo", "r")
        helpMessage = helpf.read()
        helpf.close()
        await client.send_message(
            message.author,
            "Hi Heres Some Help\nPrefix:{} (Goes Before All Commands){}".
            format(prefix, helpMessage))
        await client.send_message(
            message.channel,
            "@{} I Sent Help To Your DM's".format(message.author))

    if message.content.startswith(prefix + "randomquote"):
        lines = open('quotes.xo', encoding="utf8").read().splitlines()
        myline = random.choice(lines)
        await client.send_message(message.channel, myline)

    if message.content.startswith(prefix + "online?"):
        if len(message.content.split(" ")) != 2:
            await client.send_message(message.channel,
                                      "Invalid Amount Of Arguments")
        elif "http" not in message.content.split(" ")[1]:
            await client.send_message(message.channel, "Invalid Url")
        else:
            try:
                r = requests.get(message.content.split(" ")[1], timeout=30)
                if str(r.status_code).startswith("20"):
                    await client.send_message(
                        message.channel,
                        "{} Is Online".format(message.content.split(" ")[1]))
                else:
                    await client.send_message(
                        message.channel, "{} Is Offline Or Not Found".format(
                            message.content.split(" ")[1]))
            except:
                await client.send_message(
                    message.channel, "{} Is Offline Or Not Found".format(
                        message.content.split(" ")[1]))

    if message.content.startswith(prefix + "SupremeWeek"):
        pageSource = requests.get(
            "https://www.supremecommunity.com/season/spring-summer2018/droplists/"
        )
        pageSource = pageSource.content
        soup = bs(pageSource, "html.parser")
        links = soup.find_all('a', {'class': 'block'})[0]
        link = "https://www.supremecommunity.com" + str(links).split(
            'href="')[1].split('">')[0]
        await client.send_message(
            message.channel,
            "Hey My Supreme Features Arent Finished But I Found The Link Of The Latest Stuff {}"
            .format(link))

    if message.content.startswith(prefix + "SupremeProducts"):
        url = "http://www.supremenewyork.com/mobile_stock.json"
        s = requests.session()
        supremeStock = s.get(url)
        print(supremeStock.text)
        so = supremeStock.text.encode('UTF-8')
        supremeObject = json.loads(so)
        fnameu = "supreme_{}.txt".format(str(randint(111, 999)))
        f = open(fnameu, "w+")
        f.close()
        f = open(fnameu, "a+")
        f.write("SUPREME PRODUCT SCRAPER\n")
        f.write("OX Discord Bot BY XO\n")
        f.write(
            "Github https://github.com/TCWTEAM/OX-Discord-Bot | Twitter: @ehxohd\n"
        )
        f.write(
            "=-=-=-=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=\n"
        )
        f.write("Release Date: {} | Release Week: {}\n".format(
            supremeObject['release_date'], supremeObject['release_week']))
        f.write("\n")
        f.write("\n")
        f.write("==================\n")
        f.write("[Bags]\n")
        for item in supremeObject['products_and_categories']['Bags']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")
        f.write("\n")
        f.write("[Accessories]\n")
        for item in supremeObject['products_and_categories']['Accessories']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")
        f.write("\n")
        f.write("[Skate]\n")
        for item in supremeObject['products_and_categories']['Skate']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")
        f.write("\n")
        f.write("[Shirts]\n")
        for item in supremeObject['products_and_categories']['Shirts']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.write("\n")
        f.write("[Pants]\n")
        for item in supremeObject['products_and_categories']['Pants']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.write("\n")
        f.write("[Jackets]\n")
        for item in supremeObject['products_and_categories']['Jackets']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.write("\n")
        f.write("[Shorts]\n")
        for item in supremeObject['products_and_categories']['Shorts']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")
        f.write("\n")
        f.write("[Sweatshirts]\n")
        for item in supremeObject['products_and_categories']['Sweatshirts']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.write("\n")
        f.write("[Tops/Sweaters]\n")
        for item in supremeObject['products_and_categories']['Tops/Sweaters']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")
        f.write("\n")
        f.write("[Hats]\n")
        for item in supremeObject['products_and_categories']['Hats']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.write("\n")
        f.write("[new]\n")
        for item in supremeObject['products_and_categories']['new']:
            name = item['name']
            id = item['id']
            imageURL = item['image_url_hi'].split("//")[1]
            price = "${}".format(int(item['price']) / 100)
            f.write("------------\n")
            f.write("Name: {}\n".format(name))
            f.write("PID: {}\n".format(id))
            f.write("Price: {}\n".format(price))
            f.write("Image URL: http://{}\n".format(imageURL))
            f.write("-------------\n")

        f.close()
        f = open(fnameu, "r")
        uploadURL = hastebin.post(f.read())
        f.close()
        await client.send_message(
            message.channel,
            "I Finished Looking At Supreme. This Season Sucks But Here Are The Products On The Site {}"
            .format(uploadURL))
Example #14
0
async def paste(pstl):
    if not pstl.text[0].isalpha() and pstl.text[0] not in ("/", "#", "@", "!"):
        dogbin_final_url = ""

        textx = await pstl.get_reply_message()
        message = pstl.text
        await pstl.edit("`Pasting text . . .`")
        if message[7:]:
            message = str(message[7:])
        elif textx:
            message = str(textx.message)

        # Dogbin
        r = requests.post(DOGBIN_URL + "documents", data=message.encode('utf-8'))

        # Hastebin
        try:
            hastebin_final_url = hastebin.post(message)
        except Exception:

        if r.status_code == 200:
            response = r.json()
            key = response['key']
            dogbin_final_url = DOGBIN_URL + key

            if response['isUrl']:
                reply_text = (
                    "`Pasted successfully!`\n\n"
                    f"`Shortened URL:` {dogbin_final_url}\n\n`"
                    "Original(non-shortened) URLs`\n"
                    f"`Dogbin URL`: {DOGBIN_URL}v/{key}\n`"
                    f"Hastebin URL`: {hastebin_final_url}")
            else:
                reply_text = (
                    "`Pasted successfully!`\n\n"
                    f"`Dogbin URL`: {dogbin_final_url}\n`"
                    f"Hastebin URL`: {hastebin_final_url}")
        else:
            reply_text = (
                "`Pasted successfully!`\n\n"
                "`Dogbin URL`: `Failed to reach dogbin`"
                f"\n`Hastebin URL`: {hastebin_final_url}")

        await pstl.edit(reply_text)
        if LOGGER:
            await bot.send_message(
                LOGGER_GROUP,
                "Paste query `" + message + "` was executed successfully",
            )

@bot.on(events.NewMessage(outgoing=True, pattern="^.get_dogbin_content"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.get_dogbin_content"))
async def get_dogbin_content(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        textx = await e.get_reply_message()
        message = e.text
        await e.edit("`Getting dogbin content . . .`")
        if message[7:]:
            message = str(message[20:])
        elif textx:
            message = str(textx.message)

        format_normal = f'{DOGBIN_URL}'
        format_view = f'{DOGBIN_URL}v/'

        if message.startswith(format_view):
            message = message[len(format_view):]
        elif message.startswith(format_normal):
            message = message[len(format_normal):]

        r = requests.get(f'{DOGBIN_URL}raw/{message}')

        if r.status_code != 200:
            try:
                res = r.json()
                await e.reply(res['message'])
            except Exception:
                if r.status_code == 404:
                    await e.edit('`Failed to reach dogbin`')
                else:
                    await e.edit('`Unknown error occured`')
            r.raise_for_status()

        reply_text = "`Fetched dogbin URL content successfully!`\n\n`Content:` " + r.text

        await e.reply(reply_text)
        if LOGGER:
            await bot.send_message(
                LOGGER_GROUP,
                "Get dogbin content query for `" + message + "` was executed successfully",
            )


@bot.on(events.NewMessage(outgoing=True, pattern="^.log"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.log"))
async def log(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        textx = await e.get_reply_message()
        message = textx
        message = str(message.message)
        if LOGGER:
            await (await e.get_reply_message()).forward_to(LOGGER_GROUP)
            await e.edit("`Master!, I Logged Successfully`")
        else:
            await e.edit("`This feature requires Logging to be enabled!`")
        time.sleep(2)
        await e.delete()


@bot.on(events.NewMessage(outgoing=True, pattern="^.hash (.*)"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.hash (.*)"))
async def hash(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        hashtxt_ = e.pattern_match.group(1)
        hashtxt = open("hashdis.txt", "w+")
        hashtxt.write(hashtxt_)
        hashtxt.close()
        md5 = runapp(["md5sum", "hashdis.txt"], stdout=PIPE)
        md5 = md5.stdout.decode()
        sha1 = runapp(["sha1sum", "hashdis.txt"], stdout=PIPE)
        sha1 = sha1.stdout.decode()
        sha256 = runapp(["sha256sum", "hashdis.txt"], stdout=PIPE)
        sha256 = sha256.stdout.decode()
        sha512 = runapp(["sha512sum", "hashdis.txt"], stdout=PIPE)
        runapp(["rm", "hashdis.txt"], stdout=PIPE)
        sha512 = sha512.stdout.decode()
        ans = (
            "Text: `"
            + hashtxt_
            + "`\nMD5: `"
            + md5
            + "`SHA1: `"
            + sha1
            + "`SHA256: `"
            + sha256
            + "`SHA512: `"
            + sha512[:-1]
            + "`"
        )
        if len(ans) > 4096:
            f = open("hashes.txt", "w+")
            f.write(ans)
            f.close()
            await bot.send_file(
                e.chat_id,
                "hashes.txt",
                reply_to=e.id,
                caption="`It's too big, in a text file and hastebin instead. `"
                + hastebin.post(ans[1:-1]),
            )
            runapp(["rm", "hashes.txt"], stdout=PIPE)
        else:
            await e.reply(ans)


@bot.on(events.NewMessage(outgoing=True, pattern="^.base64 (en|de) (.*)"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.base64 (en|de) (.*)"))
async def endecrypt(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        if e.pattern_match.group(1) == "en":
            lething = str(pybase64.b64encode(bytes(e.pattern_match.group(2), "utf-8")))[
                2:
            ]
            await e.reply("Encoded: `" + lething[:-1] + "`")
        else:
            lething = str(
                pybase64.b64decode(
                    bytes(e.pattern_match.group(2), "utf-8"), validate=True
                )
            )[2:]
            await e.reply("Decoded: `" + lething[:-1] + "`")


@bot.on(events.NewMessage(outgoing=True, pattern="^.random"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.random"))
async def randomise(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        r = (e.text).split()
        index = random.randint(1, len(r) - 1)
        await e.edit("**Query: **\n`" + e.text + "`\n**Output: **\n`" + r[index] + "`")


@bot.on(events.NewMessage(outgoing=True, pattern="^.alive$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.alive$"))
async def amialive(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("`Hey Master! ,  I'm alive `")


@bot.on(events.NewMessage(outgoing=True, pattern="^.chatid$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.chatid$"))
async def chatidgetter(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("Chat ID: `" + str(e.chat_id) + "`")


@bot.on(events.NewMessage(outgoing=True, pattern="^.sleep( [0-9]+)?$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.sleep( [0-9]+)?$"))
async def sleepybot(e):
    message = e.text
    if not message[0].isalpha() and message[0] not in ("/", "#", "@", "!"):
        if not " " in e.pattern_match.group(1):
            await e.reply("Syntax: `.shutdown [seconds]`")
        else:
            counter = int(e.pattern_match.group(1))
            await e.edit("`I am sulking and snoozing....`")
            time.sleep(2)
            await bot.send_message(
                LOGGER_GROUP,
                "You put the bot to sleep for " + str(counter) + " seconds",
            )
            time.sleep(counter)


@bot.on(events.NewMessage(outgoing=True, pattern="^.shutdown$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.shutdown$"))
async def killdabot(e):
    if not e.text[0].isalpha():
        await e.edit("`Goodbye *Windows XP shutdown sound*....`")
        await bot.send_message(LOGGER_GROUP, "You REALLY shutdown the bot")
        await bot.disconnect()


@bot.on(events.NewMessage(outgoing=True, pattern="^.support$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.support$"))
async def bot_support(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("Report bugs here: @userbot_support")


@bot.on(events.NewMessage(outgoing=True, pattern="^.repo$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.repo$"))
async def repo_is_here(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("Here is my Repo https://github.com/Jeepeo/Telegram-UserBot/")


@bot.on(events.NewMessage(outgoing=True, pattern="^.supportchannel$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.supportchannel$"))
async def support_channel(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        await e.edit("Here is the userbot support channel t.me/maestro_userbot_channel")


@bot.on(events.NewMessage(outgoing=True, pattern="^.userid$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.userid$"))
async def chatidgetter(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        message = await e.get_reply_message()
        if message:
            if not message.forward:
                user_id = message.sender.id
                if message.sender.username:
                    name = "@" + message.sender.username
                else:
                    name = "**" + message.sender.first_name + "**"

            else:
                user_id = message.forward.sender.id
                if message.forward.sender.username:
                    name = "@" + message.forward.sender.username
                else:
                    name = "*" + message.forward.sender.first_name + "*"
            await e.edit(
                "**Name:** {} \n**User ID:** `{}`"
                .format(name, user_id)
            )


@bot.on(events.NewMessage(outgoing=True, pattern="^\$"))
async def rextestercli(e):
    stdin = ""
    message = e.text
    chat = await e.get_chat()

    if len(message.split()) > 1:
        regex = re.search(
            r"^\$([\w.#+]+)\s+([\s\S]+?)(?:\s+\/stdin\s+([\s\S]+))?$",
            message,
            re.IGNORECASE,
        )
        language = regex.group(1)
        code = regex.group(2)
        stdin = regex.group(3)

        try:
            rextester = Rextester(language, code, stdin)
            res = await rextester.exec()
        except UnknownLanguage as exc:
            await e.edit(str(exc))
            return

        output = ""
        output += f"**Language:**\n```{language}```"
        output += f"\n\n**Source:** \n```{code}```"

        if res.result:
            output += f"\n\n**Result:** \n```{res.result}```"

        if res.warnings:
            output += f"\n\n**Warnings:** \n```{res.warnings}```\n"

        if res.errors:
            output += f"\n\n**Errors:** \n'```{res.errors}```"

        if len(res.result) > 4096:
            with io.BytesIO(str.encode(res.result)) as out_file:
                out_file.name = "result.txt"
                await bot.send_file(chat.id, file = out_file)
                await e.edit(code)
            return

        await e.edit(output)


@bot.on(events.NewMessage(outgoing=True, pattern="^.unmutechat$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.unmutechat$"))
async def unmute_chat(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        try:
            from userbot.modules.sql_helper.keep_read_sql import unkread
        except:
            await e.edit('`Running on Non-SQL Mode!`')
        unkread(str(e.chat_id))
        await e.edit("```Unmuted this chat Successfully```")


@bot.on(events.NewMessage(outgoing=True, pattern="^.mutechat$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.mutechat$"))
async def mute_chat(e):
    if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
        try:
            from userbot.modules.sql_helper.keep_read_sql import kread
        except Exception as er:
            print(er)
            await e.edit("`Running on Non-SQL mode!`")
            return
        await e.edit(str(e.chat_id))
        kread(str(e.chat_id))
        await e.edit("`Shush! This chat will be silenced!`")
        if LOGGER:
            await bot.send_message(
                LOGGER_GROUP,
                str(e.chat_id) + " was silenced.")


@bot.on(events.NewMessage(incoming=True))
@bot.on(events.MessageEdited(incoming=True))
async def keep_read(e):
    try:
        from userbot.modules.sql_helper.keep_read_sql import is_kread
    except:
        return
    K = is_kread()
    if K:
        for i in K:
            if i.groupid == str(e.chat_id):
                await bot.send_read_acknowledge(e.chat_id)


@bot.on(events.NewMessage(outgoing=True, pattern="^.botlog$"))
@bot.on(events.MessageEdited(outgoing=True, pattern="^.botlog$"))
async def botlogs(e):
    process = await asyncsh(
        "sudo systemctl status userbot | tail -n 20",
        stdout=asyncsh_PIPE,
        stderr=asyncsh_PIPE
        )

    stdout, stderr = await process.communicate()
    result = str(stdout.decode().strip())
    f = open("err.log", "w+")
    f.write(result)
    f.close()
    await bot.send_file(
        e.chat_id,
        "err.log",
        reply_to=e.id,
        caption="`Bot logs are here!`",
    )
Example #15
0
    async def clear(self, ctx, lines=10):
        """
        This command clears a given number of lines.

        Usage: -clear [number]
        Max: 100 lines
        """

        paste_text = ''

        channel = ctx.message.channel
        member = ctx.message.author

        if member.permissions_in(channel).manage_messages:
            if lines > 100:
                lines = 100
            elif lines < 1:
                lines = 1

            channel = ctx.message.channel
            messages = []

            async for message in channel.history(limit=int(lines) + 1):
                messages.append(message)
                paste_text += f'{message.author.name} on {message.created_at}\n{message.content}\n\n'.encode(
                    'utf-8').decode()

            response = await impact.execute(
                'SELECT enabled FROM logs_channels WHERE guildid LIKE {}'.
                format(message.guild.id),
                fetchone=True)
            enabled = response[0] == 1
            await impact.execute(
                'UPDATE logs_channels SET enabled = false WHERE guildid LIKE {}'
                .format(ctx.message.guild.id),
                commit=True)
            await channel.delete_messages(messages)

            embed = discord.Embed(
                title='Moderation',
                description='{} messages deleted!'.format(lines),
                color=color)
            await ctx.send(embed=embed)
            if enabled:
                await impact.execute(
                    'UPDATE logs_channels SET enabled = true WHERE guildid LIKE {}'
                    .format(ctx.message.guild.id),
                    commit=True)
                logs_channel = await get_logs_channel(ctx.message.guild)
                paste = hastebin.post(paste_text) + '.txt'
                e = discord.Embed(
                    title='Messages Cleared',
                    description=
                    'On {}, {} cleared {} messages. These messages can be viewed here: {}'
                    .format(
                        str(datetime.datetime.now())[0:16],
                        ctx.message.author.mention, lines, paste),
                    color=color)
                await logs_channel.send(embed=e)

        else:
            e = discord.Embed(
                title='No Permission',
                description=
                'You don\'t have permission to manage messages in this channel!',
                color=color)
            await ctx.send(embed=e)
Example #16
0
async def haste_paste(e):
    message=e.text
    await e.edit('`Sending to bin . . .`')
    text=str(message[7:])
    await e.edit('`Sent to bin! Check it here: `' + hastebin.post(text))
Example #17
0
def haste(arg):
    try:
        return hastebin.post(arg)
    except Exception as e:
        print(e)